= Cirodown

Markup language + static site generator to write complex structured wikis/books/blogs, that is \x[saner] and \x[design-goals][more powerful] than Markdown and Asciidoctor, with reference implementation in JavaScript.

* https://cirosantilli.com[]: showcase demo document with interesting content. Primary inspiration for Cirodown development.
  * https://cirosantilli.com/oxford-nanopore-river-bacteria[]: a tutorial style part of the above. Note how internal links integrate seamlessly into the more global topic of biology.
  * https://github.com/cirosantilli/cirosantilli.github.io[] and https://github.com/cirosantilli/cirosantilli.github.io/blob/dev/oxford-nanopore-river-bacteria.ciro[]: source of the above showcase documents
* \x[design-goals]{full}: feature overview
* https://github.com/cirosantilli/cirodown[]: Cirodown source code
* https://github.com/cirosantilli/cirodown/blob/master/README.ciro[]: source for this document
* https://cirosantilli.com/cirodown[]: rendered version of this document
* https://cirosantilli.com/cirodown/editor[]: live in-browser demo
* https://cirosantilli.com/cirodown-template[]: good template to get started, see \x[quick-start]{full}

= Quick start
{parent=cirodown}

= Play with the template
{parent=quick-start}

Learn the syntax basics in 5 minutes: https://cirosantilli.com/cirodown/editor[].

Play with https://github.com/cirosantilli/cirodown-template[a Cirodown template] locally:
``
git clone https://github.com/cirosantilli/cirodown-template
cd cirodown-template
npm install
npx cirodown .
firefox index.html
``
That template can be seen rendered live at: http://cirosantilli.com/cirodown-generate-multifile/ Other templates are documented at: \x[generate].

To \x[publish-to-github-pages] on your repository you can just fork the repository https://github.com/cirosantilli/cirodown-template to your own https://github.com/johndoe/cirodown-template and then:
``
git remote set-url origin git@github.com:johndoe/cirodown-template.git
npx cirodown --publish
``
and it should now be visible at: https://johndoe.github.io/cirodown-template

Then, every time you make a change you can publish the new version with:
``
git add .
git commit --message 'hacked stuff'
cirodown --publish .
``
or equivalently with the \x[publish-commit] shortcut:
``
cirodown --publish-commit 'hacked stuff'
``

If you want to publish to your root page https://johndoe.github.io instead of https://johndoe.github.io/cirodown-template you need to rename the `master` branch to `dev` as mentioned at \x[publish-to-github-pages-root-page]:
``
git remote set-url origin git@github.com:johndoe/johndoe.github.io.git

# Rename master to dev, and delete the old master.
git checkout -b dev
git push origin dev:dev
git branch -D master
git push --delete origin master

npx cirodown --publish
``

The following files of the template control the global style of the output, and you are free to edit them:
* `main.liquid.html`: global HTML template in https://shopify.github.io/liquid/[Liquid format]. Available variables are documented at \x[template], and it is being selected in that repository with :
  ``
  "template": "main.liquid.html"
  ``
  in the \x[cirodown-json] configuration file.
* `main.scss`: https://sass-lang.com/[Sass] file that gets converted to raw CSS `main.css` by `npx cirodown .`.

  Sass is just much more convenient to write than raw CSS.

  That file gets included into the global HTML template inside `main.liquid.html` at:
  ``
  <link rel="stylesheet" href="{{ root_relpath }}main.css">
  ``

= Important command line options
{parent=quick-start}

When you run:
``
npx cirodown .
``
it converts all files in the current directory separately, e.g.:
* `README.ciro` to `index.html`, since `README` is a magic name that we want to show on the root URL
* `not-readme.ciro` to `not-readme.html`, as this one is a regular name unlike `README`
* `main.scss` to `main.css`

If one of the input files starts getting too large, usually the toplevel `README.ciro` in which you dump everything by default like Ciro does, you can speed up development and just compile files individually with either:
``
npx cirodown README.ciro
npx cirodown not-readme.ciro
``
Note however that  when `README.ciro` has a \x[internal-cross-file-reference] to something defined in `not-readme.ciro`, e.g. via `\x[h2-in-not-the-README]`, then you must first do a first pass once with `npx cirodown .` to parse all files and extract all necessary IDs to the \x[id-database].

When dealing with large files, you might also be interested in the following amazing options:
* \x[split-headers]
* \x[h-splitdefault-argument]

To produce a single standalone output file that contains everything in a directory run:
``
npx cirodown --embed-resources --embed-includes README.ciro
xdg-open index.html
``
You can now just give `index.html` to any reader and they should be able to view it offline without installing anything. The flags are:
* \x[embed-includes]: without this, `\Include[not-readme]` shows as a link to the file `not-readme.html` which comes from `not-readme.ciro` With the flag, `not-readme.ciro` output gets embedded into the output `index.html` directly
* \x[embed-resources]: by default, we link to CSS and JavaScript that lives inside `node_modules`. With this flag, that CSS and JavaScript is copied inline into the document instead. One day we will try to handle \x[image]{p} that way as well

= Useless knowledge
{parent=quick-start}

Install the NPM package globally and use it from the command line for a quick conversion:
``
npm install -g cirodown
printf 'ab\ncd\n' | cirodown --body-only
``
or to a file:
``
printf 'ab\ncd\n' | cirodown > tmp.html
``
You almost never want to do this except when \x[developing-cirodown], as it won't be clear what version of `cirodown` the document should be compiled with. Just be a good infant and use Cirodown \x[play-with-the-template][with the template] that contains a `package.json` via `npx`, OK?

Furthermore, the default install of Chromium on Ubuntu 21.04 uses Snap and blocks access to dotfiles. For example, in a sane NVM install, our global CSS would live under `/home/ciro/.nvm/versions/node/v14.17.0/lib/node_modules/cirodown/dist/cirodown.css`, which gets blocked because of the `.nvm` part:
* https://forum.snapcraft.io/t/dot-files/7062
* https://bugs.launchpad.net/snapd/+bug/1607067
* https://superuser.com/questions/1546550/chromium-81-wont-display-dotfiles-anymore
* https://askubuntu.com/questions/1184357/why-cant-chromium-suddenly-access-any-partition-except-for-home
* https://askubuntu.com/questions/1214346/as-a-user-is-there-any-way-to-change-the-confinement-of-a-snap-package
One workaround is to use \x[embed-resources], but this of course generates larger outputs.

To run master globally for development see: \x[run-cirodown-master]{full}. This one actually works despite the dotfile thing since your development path is normally outside of dotfiles.

Try out the JavaScript API with \a[api_hello.js]:
``
npm install cirodown
./api_hello.js
``

= Design goals
{parent=cirodown}

Cirodown is designed entirely to allow writing complex professional HTML and PDF scientific books, blogs, articles and encyclopedias.

Cirodown aims to be the ultimate \x[latex-output-format][LaTeX] "killer", allowing books to be finally published as either HTML or PDF painlessly (LaTeX being only a backend to PDF generation).

= Features
{parent=design-goals}

* \x[internal-cross-reference][references] to \x[header]{p}, \x[image]{p}, etc. with amazing \x[error-reporting][error checking and reporting]: never break internal links without knoing again, and quickly find out what broke when you do
* KaTeX server side \x[mathematics]
* multi-file features out of the box so you don't need a separate wrapper like Jekyll to make a multi-page website:
  * \x[internal-cross-file-reference]{p}
  * `inotifywait` watch rebuild server
  * single-source multi-format output based on \x[include]{p} and build options:
    * one HTML per source with includes rendered as links between pages
    * \x[embed-includes] single file output. Includes are parsed smartly, not just source copy pasted, e.g. included headers are shifted from `h1` to `h2` correctly
    * \x[split-headers] option to output each header of an input file into a separate output file
    * supports both local serverless rendering to HTML files for local viewing, and server oriented rendering such as GitHub pages, e.g. \x[internal-cross-reference]{p} automatically get `.html` extension and or not
  * cross file configuration files to factor out common page parts like headers, footers and other metadata
  * \x[table-of-contents] that crosses input files (TODO https://github.com/cirosantilli/cirodown/issues/126[])
* advanced header/ID related features:
  * \x[scope]{p}
  * \x[synonym]{p}
  * tags are regular headers: \x[x-child-argument]
  * \x[unlimited-header-levels]
  * \x[id-based-header-levels]
* is written in JavaScript and therefore runs natively on the browser to allow live previews
* helps you with the publishing:
  * `./cirodown --publish` helper for single command publishing to the configured target (default GitHub pages): \x[publish]
  * Cirodown tries to deal with media such as images and video intelligently for you, see e.g.: \x[where-to-store-images]

= Saner
{parent=design-goals}

Originally, Cirodown was is meant to be both saner and more powerful than Markdown and Asciidoctor.

But alas, as Ciro started implementing and using it, he started to bring some Markdown \x[insane-macro-shortcuts][insanity he missed back in].

And so this "degraded" slightly into a language slightly saner than Asciidoctor but with an amazing Node.js implementation that makes it better for book writing and website publishing.

Notably, we hope that our escaping will be a bit saner backslash escapes everything instead of Asciidoctor's "different escapes for every case" approach: https://github.com/asciidoctor/asciidoctor/issues/901

But hopefully, having starting from a saner point will still produce a saner end result, e.g. there are sane constructs for every insane one.

It is intended that this will be an acceptable downside as Cirodown will be used primarily large complex content such as books rather than forum posts, and will therefore primarily written either:
* in text editors locally, where users have more features than in random browser textareas
* in a dedicated website that will revolutionize education, and therefore have a good JavaScript editing interface: https://github.com/cirosantilli/write-free-science-books-to-get-famous-website

For example, originally Cirodown had exactly five magic characters, with similar functions as in LaTeX:
* `\` backslash to start a macro, like LaTeX
* `{` and `}`: left and right square brackets to delimit \x[positional-vs-named-arguments][optional macro arguments]
* `[` and `]`: left and right curly braces bracket to start an optional arguments
and double blank newlines for \x[paragraph]{p} if you are pedantic, but this later degenerated into many more with \x[insane-macro-shortcuts].

We would like to have only square brackets for both optional and mandatory to have even less magic characters, but that would make the language difficult to parse for computer and humans. LaTeX was right for once!

This produces a very regular syntax that is easy to learn, including doing:
* arbitrary nesting of elements
* adding arbitrary properties to elements

This sanity also makes the end tail learning curve of the endless edge cases found in Markdown and Asciidoctor disappear.

The language is designed to be philosophically isomorphic to HTML to:
* further reduce the learning curve
* ensure that most of HTML constructs can be reached, including arbitrary nesting

More precisely:
* macro names map to tag names, e.g.: `\\a` to `<a`
* one of the arguments of macros, maps to the content of the HTML element, and the others map to attributes.

  E.g., in a link:
  ``\a[http://example.com][Link text\]``
  the first macro argument:
  ``http://example.com``
  maps to the `href` of `<a`, and the second macro argument:
  ``Link text``
  maps to the internal content of `<a>Link text<>`.

= More powerful
{parent=design-goals}

The \x[saner][high sanity of Cirodown], also makes creating new macro extensions extremely easy and intuitive.

All built-in language features use the exact same API as new extensions, which ensures that the extension API is sane forever.

Markdown is clearly missing many key features such as block attributes and \x[internal-cross-reference]{p}, and has no standardized extension mechanism.

The "more powerful than Asciidoctor" part is only partially true, since Asciidoctor is very featureful can do basically anything through extensions.

The difference is mostly that Cirodown is completely and entirely focused on making amazing scientific books, and so will have key features for that application out-of-the box, notably:
* amazing header/ToC/ID features including proper error reports: never have a internal broken link or duplicate ID again
* \x[mathematics][server side pre-rendered maths with KaTeX]: all divs and spans are ready, browser only applies CSS, no JavaScript gets executed
* \x[publish]: we take care of website publishing for you out-of-the-box, no need to integrate into an external project like Jekyll
* \x[split-headers]:
** https://github.com/asciidoctor/asciidoctor/issues/626 feature request
** https://github.com/owenh000/asciidoctor-multipage third party plugin that does it
and we feel that some of those features have required specialized code that could not be easily implemented as a standalone macro.

Another advantage over Asciidoctor is that the reference implementation of Cirodown is in JavaScript, and can therefore be used on browser live preview out of the box. Asciidoctor does Transpile to JS with https://github.com/opal/opal[Opal], but who wants to deal with that layer of complexity?

= Related projects
{parent=design-goals}

Static wiki generators: this is perhaps the best way of classifying this project :-)
* https://github.com/gollum/gollum[]: already has a local server editor! But no WYSIWYG nor live preview. Git integration by default, so when you save on the UI already generates a Git commit. We could achieve that with: https://github.com/isomorphic-git/isomorphic-git[], would be really nice.
* https://github.com/wcchin/markypydia
* https://obsidian.md/ closed source, Markdown with \x[internal-cross-file-reference] + a SaaS. Appears to require payment for any publishing. 28k followers 2021: https://twitter.com/obsdmd[]. Founders are likely Canadians of Asian descent from Waterloo University: https://www.linkedin.com/in/lishid/ | https://www.linkedin.com/in/ericaxu/ also working in parallel on https://dynalist.io/ 2020 review at: https://www.youtube.com/watch?v=aK2fOQRNSxc Has offline editor with side-by-side preview. Compares with https://roamresearch.com/[Roam] and https://roamresearch.com/[Notion], but can't find any public publishing on those, seem to be enterprise only things.
* https://www.gitbook.com/

Static book generators:
* https://github.com/rstudio/bookdown[], https://bookdown.org/[]. Very similar feature set to what we want!!! Transpiles to markdown, and then goes through Pandoc: https://bookdown.org/yihui/bookdown/pandoc.html[], thus will never run on browser without huge translation layers. But does have an obscene amount of output formats however.
* https://gohugo.io/[Hugo]. Pretty good, similar feature set to ours. But Go based, so hard on browser, and adds adhoc features on top of markdown once again
* https://en.wikipedia.org/wiki/Personal_wiki
  * https://github.com/vimwiki/vimwiki
* https://github.com/hplgit/doconce
* https://www.gwern.net/About#source is pretty interesting, uses https://github.com/jaspervdj/Hakyll/ + some custom stuff.
* https://github.com/JerrySievert/bookmarkdown

Less related but of interest, similar philosophy to what Ciro wants, but no explicitly reusable system:
* http://www.uprtcl.io/
* https://libretexts.org
* https://physics.info/
* https://hypertextbook.com/
* https://tutorial.math.lamar.edu/

= Motivation
{parent=design-goals}

Ciro Santilli developed Cirodown to perfectly satisfy his writing style, which is basically "create one humongous document where you document everything you know about a subject so everyone can understand it, and just keep adding to it".

https://cirosantilli.com[] is the first major document that he has created in Cirodown.

He decided to finally create this new system after having repeatedly facing limitations of Asciidoctor which were ignored/wontfixed upstream, because Ciro's  writing style is not as common/targeted by Asciidoctor.

Following large documents Ciro worked extensively on:
* https://github.com/cirosantilli/china-dictatorship
* https://github.com/cirosantilli/linux-kernel-module-cheat
made the limitations of Asciidoctor clear to Ciro, and were major motivation in this work.

The key limitations have repeatedly annoyed Ciro were:
* cannot go over header level 6, addressed at: \x[unlimited-header-levels]
* the need for \x[split-headers] to avoid one too large HTML output that will never get indexed properly by search engines, and takes a few seconds to load on any browser, which is unacceptable user experience

= Macro
{parent=cirodown}

This section documents all Cirodown macros.

The general macro syntax is described at \x[cirodown-syntax]{full}.

= Link
{parent=macro}

= `\a`
{synonym}
{title2}

\x[insane-macro-shortcuts][Insane] autolink (link text is the same as the link):
\CirodownExample[[
The website http://example.com is cool. See also:

\Q[http://example.com/2]
]]
Exact parsing rules described at: \x[insane-link-parsing-rules]{full}.

Equivalent sane version:
\CirodownExample[[[
The website \a[http://example.com] is cool.

\Q[\a[http://example.com/2]]
]]]

Insane link with custom text:
\CirodownExample[[
The website http://example.com[example.com] is cool.
]]
Equivalent sane version:
\CirodownExample[[
The website \a[http://example.com][example.com] is cool.
]]
If the custom text is empty, an autolink is generated. This is often useful if you want your link to be followed by punctuation:
\CirodownExample[[
The website is really cool: http://example.com[].
]]
This could also be achieved with the sane syntax of course, but this pattern saves a tiny bit of typing.

Link with multiple paragraphs inside it:
\CirodownExample[[
\a[http://example.com][Multiple

paragraphs]
]]

= `\a` `check` argument
{parent=link}

If `{check=0}` is given, this disables the local file existence check that is done by default for \x[relative-link]{p}.

If `check` is not given explicitly, Cirodown does the check by default if the link is not a \x[url-with-protocol] For example, the following are not checked:
* `http://cirosantilli.com`
* `https://cirosantilli.com`
* `file:///etc/fstab`
* `ftp://cirosantilli.com`
and the following are:
* `index.js`
* `../index.js`
* `path/to/index.js`
* `/path/to/index.js`. Since it stats with a `/`, this path has to exist relative to \x[project-toplevel-directory], not relative to the current `.ciro` source.
* `//example.com/path/to/index.js`. This gets treated the same as `/example.com/path/to/index.js`.

For example, it is often the case in computer programming tutorials that we want to refer to source files in the current directory, so you could have in your `README.ciro`:
``
See this awesome source file: \a[index.js]
``
and then if `index.js` does not exist in the project, compilation leads to an error.

This check is important because as you start documenting several source files, it is almost inevitable getting wrong paths due to renames or typos without this type of error checking

The most common use case for disabling checks is as follows.

https://github.com/cirosantilli/cirosantilli.github.io/blob/da296c3c933704484d5cd1a42754f60ec00f672b/README.ciro was rendered at https://cirosantilli.com[], and contains links to https://cirosantilli.com/markdown-style-guide[], whose source lives in a separate non-Cirodown repository: https://github.com/cirosantilli/markdown-style-guide/

Therefore, if we did from `README.ciro`:
``
See this awesome style guide: \a[markdown-style-guide]
``
we do not want Cirodown do check that the file `markdown-style-guide` exists in the local filesystem.

For this reason, we have instead to write:
``
See this awesome style guide: \a[markdown-style-guide]{check=0}
``

The general lesson is clear: in a server, paths could be re-routed to anything, including content that lies outside of a Cirodown project.

= `\a` `ref` argument
{parent=link}

Analogous to the \x[x-ref-argument], e.g.:
\CirodownExample[[
Trump said this and that.https://en.wikipedia.org/wiki/Donald_Trump_Access_Hollywood_tape#Trump's_responses{ref}https://web.archive.org/web/20161007210105/https://www.donaldjtrump.com/press-releases/statement-from-donald-j.-trump{ref}
]]

= `\a` `relative` argument
{parent=link}

If given, this \x[boolean-named-argument] forces a given link to be a \x[relative-link] or not.

Otherwise, the link is automatically guessed based on the address given as explained below.

= Relative link
{parent=a-relative-argument}

A relative link is a link that points to a resource that will be present a final URL relative to the input `.ciro` file.

For example, it is often the case in computer programming tutorials that we want to refer to source files in the current directory.

So from our `README.ciro`, we could want to write something like:
\CirodownExample[[
Have a look at this amazing source file: \a[index.js].
]]
and here `\a[cirodown]` is a relative link.

A non-relative link is something like:
\CirodownExample[[
This is great website: https://cirosantilli.com
]]
which points to an absolute URL.

A link being relative has the following effects
* the correct relative path to the file is used when using nested \x[scope]{p} with \x[split-headers]. For example, if we have:
  ``
  = h1

  == h2
  {scope}

  === h3

  \a[index.js]
  ``
  then in split header mode, `h3` will be rendered to `h2/h3.html`.

  Therefore, if we didn't do anything about it, the link to `index.js` would render as `href="index.js"` and thus point to `h2/index.js` instead of the correct `index.js`.

  Instead, Cirodown automatically converts it to the correct `href="../index.js"`

Cirodown considers a link relative by default if:
* it is not a \x[url-with-protocol]
* it does not start with a slash `/`

Therefore, the following are not relative links by default:
* `http://cirosantilli.com`
* `https://cirosantilli.com`
* `file:///etc/fstab`
* `ftp://cirosantilli.com`
* `/path/to/index.js`
* `//example.com/path/to/index.js`
and the following are:
* `index.js`
* `../index.js`
* `path/to/index.js`

Implemented at: https://github.com/cirosantilli/cirodown/issues/87[].

= URL with protocol
{parent=relative-link}

A URL with protocol is a URL that matches the regular expression `^[a-zA-Z]+://`. The following are examples of URLs with protocol:
* `http://cirosantilli.com`
* `https://cirosantilli.com`
* `file:///etc/fstab`
* `ftp://cirosantilli.com`

The following aren't:
* `index.js`
* `../index.js`
* `path/to/index.js`
* `/path/to/index.js`
* `//example.com/path/to/index.js`. This one is a bit tricky. Web browsers would consider this as a https://stackoverflow.com/questions/28446314/why-use-protocol-relative-urls-at-all[protocol-relative URL], which technically implies a protocol, although that protocol would be different depending how you are viewing the file, e.g. locally through `file://` vs on a with website `https://`.

  For simplicity's sake, we just consider it as a URL without protocol.

= Insane link parsing rules
{parent=link}

Insane start at any of the recognized protocols are the ones shown at: \x[known-url-protocols]{full}.
* `http://`
* `https://`
absolutely anywhere if not escaped, e.g.:
``
ahttp://example.com
``
renders something like:
``
a <a href="http://example.com">
``
To prevent expansion, you have to escape the protocol with a backslash `\\`, e.g.:
``
\http://example.com
``
Empty domains like:
``
http://
``
don't becomes links however. But this one does:
``
http://a
``

Insane links end when either the end of the document or one of the following characters is found:
* space ` `
* newline `\n`
* open or close square bracket `[` or `]`
* open or close curly braces `{` or `}`

As a consequence, to have an insane link followed immediately by a punctuation like a period you should use an empty argument as in:
\CirodownExample[[
Check out this website: http://example.com[].
]]
otherwise the punctuation will go in it. Another common use case is:
\CirodownExample[[
As mentioned on the tutorial (http://example.com[see this link]).
]]

If you want your link to include one of the terminating characters, e.g. `]`, all characters can be escaped with a backslash, e.g.:
\CirodownExample[[
Hello http://example.com/\]a\}b\\c\ d world.
]]

Note that the `http://example.com` inside `\a[http://example.com]` only works because we do some post-processing magic that prevents its expansion, otherwise the link would expand twice:
\CirodownExample[[
\P[http://example.com]

\a[http://example.com]
]]
This magic can be observed with \x[help-macros] by seeing that the `href` argument of the `a` macro has the property: 
``
"elide_link_only": true,
``

= Bold
{parent=macro}
{title2=`\b`}

\CirodownExample[[
Some \b[bold] text.
]]

= Code block
{parent=macro}
{title2=\c[[``]], \c[[`]], `\C`, `\c`}

Inline code (code that should appear in the middle of a paragraph rather than on its own line) is done with a single backtick (\c[[`]]) \x[insane-macro-shortcuts][insane macro shortcut]:
\CirodownExample[[
My inline `x = 'hello\n'` is awesome.
]]
and block code (code that should appear on their own line) is done with two or more backticks (\c[[``]]):
\CirodownExample[[
``
f() {
  return 'hello\n';
}
``
]]

The sane version of inline code is a lower case `c`:
\CirodownExample[[[
My inline \c[[x = 'hello\n']] is awesome.
]]]
and the sane version of block math is with an upper case `C`:
\CirodownExample[[[
\C[[
f() {
  return 'hello\n';
}
]]
]]]

The capital vs lower case theme is also used in other elements, see: \x[block-vs-inline-macros].

If the content of the sane code block has many characters that you would need to \x[escape-characters][escape], you will often want to use \x[literal-arguments], which work just like the do for any other argument. For example:
\CirodownExample[[[[
\C[[[
A paragraph.

\C[[
And now, some long, long code, with lots
of chars that you would need to escape:
\ [  ] {  }
]]

A paragraph.
]]]
]]]]
Note that the initial newline is skipped automatically in code blocks, just as for any other element, due to: \x[argument-leading-newline-removal], so you don't have to worry about it.

The distinction between inline `\c` and block `\C` code blocks is needed because in HTML, https://stackoverflow.com/questions/5371787/can-i-have-a-pre-tag-inside-a-p-tag-in-tumblr/58603596#58603596[`pre` cannot go inside `P`].

We could have chosen to do some magic to differentiate between them, e.g. checking if the block is the only element in a paragraph, but we decided not to do that to keep the language saner.

And now a code block outside of \x[cirodownexample] to test how it looks directly under \x[toplevel]:

``
Hello

Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
    HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello
Hello
``

\Comment[[[[
TODO implement.
We can have cross references to code blocks as for other elements such as \x[image]{p}:
\CirodownExample[[[
See this awesome code \x[my-code]:
``
ab
cd
``
{id=my-code}
]]]
]]]]

Block code can have a title, e.g. see this one: \x[code-my-nice-code]{full}:
\CirodownExample[[
``
ab
cd
``
{id=code-my-nice-code}
{title=My nice code block.}
]]

= `\CirodownExample`
{parent=macro}

Shows both the Cirodown code and its rendered output, e.g.:
\CirodownExample[[[
\CirodownExample[[
Some `ineline` code.
]]
]]]

Its input should be thought of as a literal code string, and it then injects the rendered output in the document.

This macro is used extensively in the Cirodown documentation.

= Comment
{parent=macro}
{title2=`\Comment`}

The `Comment` and `comment` macros are regular macros that does not produce any output. Capitalization is explained at: \x[block-vs-inline-macros]{full}.

You will therefore mostly want to use it with a \x[literal-arguments][literal argument], which will, as for any other macro, ignore any macros inside of it.
\CirodownExample[[[
Before comment.

\Comment[[
Inside comment.
]]

After comment.
]]]

And an inline one:
\CirodownExample[[[
My inline \comment[[inside comment]] is awesome.

\comment[[inside comment]] inline at the start.
]]]

= Header
{parent=macro}
{title2=`\H`}

\x[insane-macro-shortcuts][Insane] with `= ` (equal sign space):
``
= My h1

== My h2

=== My h3
``
Insane headers end at the first newline found. They cannot therefore contain raw newline tokens.

Equivalent sane:
``
\H[1][My h1]

\H[2][My h2]

\H[3][My h3]
``

Custom ID for \x[internal-cross-reference]{p} on insane headers:
``
= My h1
{id=h1}

== My h2
{id=h2}

=== My h3
{id=h3}
``

Sane equivalent:
``
\H[1][My h1]{id=h1}

\H[2][My h2]{id=h2}

\H[3][My h3]{id=h3}
``

= Automatic ID from title
{parent=header}

If a \x[the-toplevel-header][non-toplevel] macro has the `title` property is present but no explicit `id`, an ID is created automatically from the `title`, by applying the following transformations:
* do a \x[id-output-format] conversion on the title to remove for example any HTML tags that would be present in the conversion output
* convert all characters to lowercase. This uses \x[javascript-case-conversion].
* convert consecutive sequences of all non `a-z0-9` ASCII characters to a single hyphen `-`. Note that this leaves non-ASCII characters untouched.
* strip leading or trailing hyphens
Note how those rules leave non ASCII Unicode characters untouched, as capitalization and determining if something "is a letter or not" in those cases can be tricky.

For toplevel headers, see: \x[the-id-of-the-first-header-is-derived-from-the-filename].

So for example, the following automatic IDs would be generated: \x[table-examples-of-automatically-generated-ids].

\Table{title=Examples of automatically generated IDs.}
[
|| title
|| id
|| comments

| My favorite title
| my-favorite-title
|

| Ciro's markdown is awesome
| ciro-s-markdown-is-awesome
| `'` is an ASCII character, but it is not in `a-z0-9`, therefore it gets converted to a hyphen `-`

| É你
| é你
| The Latin https://en.wikipedia.org/wiki/Acute_accent[acute accented] `e`, `É`, is converted to its lower case form `é` as per the \x[javascript-case-conversion]. The Chinese `你` is left untouched as Chinese characters have no case.
]

For \x[the-toplevel-header][the toplevel header], its ID is derived from the basename of the Cirodown file without extension instead of from the `title` argument.

= Unlimited header levels
{parent=header}

There is no limit to how many levels we can have, for either sane or insane headers!

HTML is randomly limited to `h6`, so Cirodown just renders higher levels as an `h6` with a `data-level` attribute to indicate the actual level for possible CSS styling:
``
<h6 data-level="7">My title</h6>
``

The recommended style is to use insane headers up to `h6`, and then move to sane one for higher levels though, otherwise it becomes very hard to count the `=` signs.

To avoid this, we considered making the insane syntax be instead:
``
= 1 My h1
= 2 My h2
= 3 My h3
``
but it just didn't feel as good, and is a bit harder to type than just smashing `=` n times for lower levels, which is the most common use case. So we just copied markdown.

= My h3
{parent=unlimited-header-levels}

= My h4
{parent=my-h3}

= My h5
{parent=my-h4}

= My h6
{parent=my-h5}

= My h7
{parent=my-h6}

= My h8
{parent=my-h7}

= My h9
{parent=my-h8}

= My h10
{parent=my-h9}

= My h11
{parent=my-h10}

= My h12
{parent=my-h11}

= My h13
{parent=my-h12}

= Skipping header levels
{parent=header}

The very first header of a document can be of any level, although we highly recommend your document to start with a `\H[1]`, and to contain exactly just one `\H[1]`, as this has implications such as:
* `\H[1]` is used for the document title: \x[html-document-title]
* `\H[1]` does not show on the \x[table-of-contents]

After the initial header however, you must not skip a header level, e.g. the following would give an error because it skips level 3:
``
= my 1

== my 1

==== my 4
``

= The toplevel header
{parent=header}

If the document has only a single header of the highest level, e.g. like the following has only a single `h2`:
``
== My 2

=== My 3 1

=== My 3 2
``
then this has some magical effects.

= The toplevel header IDs don't show
{parent=the-toplevel-header}

Header IDs won't show for the toplevel level. For example, the headers would render like:
``
My 2

1. My 3 1

2. My 3 2
``
rather than:
``
1. My 2

1.2. My 3 1

1.2. My 3 2
``
This is because in this case, we guess that the `h2` is the toplevel.

= The ID of the first header is derived from the filename
{parent=the-toplevel-header}

TODO: we kind of wanted this to be the ID of the toplevel header instead of the first header, but this would require an extra postprocessing pass (to determine if the first header is toplevel or not), which might affect performance, so we are not doing it right now.

When the Cirodown input comes from a file (and not e.g. stdin), the default ID of the first header in the document is derived from the basename of the Cirodown input source file rather than from its title.

This is specially relevant when \x[include][including] other files.

For example, in file named `my-file.ciro` which contains:
``
= Awesome cirodown file
]]
``
the ID of the header is `my-file` rather than `awesome-cirodown-file`. See also: \x[automatic-id-from-title].

If the file is an \x[index-files][index file] other than \x[the-toplevel-index-file], then the basename of the parent directory is used instead, e.g. the toplevel ID of a file:
``my-subdir/README.ciro``
would be:
``#my-subdir``
rather than:
``#README.ciro``

For the toplevel index file however, the ID is just taken from the header itself as usual. This is done because you often can't general control the directory name of a project.

For example, a \x[publish-to-github-pages][GitHub pages] root directory must be named as `<username>.github.io`. And users may need to rename directories to avoid naming conflicts.

As a consequence of this, the toplevel index file cannot \x[include][be included in other files].

= `\H` arguments
{parent=header}

= `\H` `c` argument
{parent=h-arguments}

If given, makes the header capitalized by default on \x[internal-cross-file-reference]{p}.

More details at: \x[cross-reference-title-inflection]{full}.

= `\H` `disambiguate` argument
{parent=h-arguments}

Sometimes the short version of a name is ambiguous, and you need to add some extra text to make both its title and ID unique.

For example, the word "Python" could either refer to:
* the programming language: https://en.wikipedia.org/wiki/Python_(programming_language)
* the genus of snakes: https://en.wikipedia.org/wiki/Python_(genus)

The `disambiguate` \x[positional-vs-named-arguments][name argument], which is automatically defined for all macros, helps you deal more neatly with such problems.

Have a look at this example:
``
My favorite snakes are \x[python-genus]{p}!

My favorite programming language is \x[python-programming-language]!

\x[python-genus]{full}

\x[python-programming-language]{full}

== Python
{disambiguate=genus}

== Python
{c}
{disambiguate=programming language}
{title2=.py}
{wiki}
``
which renders as:
\Q[
My favorite snakes are \x[python-genus]{p}!

My favorite programming language is \x[python-programming-language]!

\x[python-genus]{full}

\x[python-programming-language]{full}

= Python
{disambiguate=genus}
{parent=h-disambiguate-argument}

= Python
{c}
{disambiguate=programming language}
{parent=h-disambiguate-argument}
{title2=.py}
{wiki}
]
from which we observe how `disambiguate`:
* gets added to the ID after conversion following the same rules as \x[automatic-id-from-title]
* shows up on the header between parenthesis, much like Wikipedia, as well as in \x[x-full-argument][`full` cross references]
* does not show up on non-`full` references. This makes it much more likely that you will be able to reuse the title automatically on a cross reference without `content`: we wouldn't want to say "My favorite programming language is Python (programming language)" all the time, would we?
* gets added to the default \x[h-wiki-argument] inside parenthesis, following Wikipedia convention, therefore increasing the likelihood that you will be able to go with the default Wikipedia value

Besides disambiguating headers, the `disambiguate` argument has a second related application: disambiguating IDs of images. For example:
\CirodownExample[[
\x[image-the-title-of-my-disambiguate-image]{full=0}

\x[image-the-title-of-my-disambiguate-image-2]{full=0}

\x[image-the-title-of-my-disambiguate-image]{full}

\x[image-the-title-of-my-disambiguate-image-2]{full}

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{title=The title of my disambiguate image.}

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{title=The title of my disambiguate image.}
{disambiguate=2}
]]
Note that unlike for headers, `disambiguate` does not appear on the title of images at all. It serves only to create an unique ID that can be later referred to. Headers are actually the only case where `disambiguate` shows up on the visible rendered output.

This use case is even more useful when `title-from-src` is enable by default for the \x[cirodown-json/media-providers] entry, so you don't have to repeat titles several times over and over.

= `\H` `parent` argument
{c}
{parent=h-arguments}

= ID-based header levels
{c}
{synonym}
{title2}

In addition to the basic way of specifying header levels with an explicit level number as mentioned at \x[header]{full}, Cirodown also supports a more indirect ID-based mechanism with the `parent` argument of the `\H` element.

We hightly recommend using `parent` for all but the most trivial documents.

For example, the following fixed level syntax:
``
= My h1

== My h2 1

== My h2 2

=== My h3 2 1
``
is equivalent to the following ID-based version:
``
= My h1

= My h2 1
{parent=my-h1}

= My h2 2
{parent=my-h1}

= My h3 2 1
{parent=my-h2-h}
``

The main advantages of this syntax are felt when you have a huge document with \x[unlimited-header-levels][very large header depths]. In that case:
* it becomes easy to get levels wrong with so many large level numbers to deal with. It is much harder to get an ID wrong.
* when you want to move headers around to improve organization, things are quite painful without a refactoring tool (which we intend to provide in the \x[browser-editor-with-preview]), as you need to fix up the levels of every single header.

  If you are using the ID-based syntax however, you only have to move the chunk of headers, and change the `parent` argument of a single top-level header being moved.

Note that when the `parent=` argument is given, the header level must be `1`, otherwise Cirodown assumes that something is weird and gives an error. E.g. the following gives an error:
``
= My h1

== My h2
{parent=my-h1}
``
because the second header has level `2` instead of the required `= My h2`.

When \x[scope]{p} are involved, the rules are the same as those of internal reference resolution, including the leading `/` to break out of the scope in case of conflicts.

See also: \x[header-explicit-levels-vs-nesting-design-choice]{full} for further rationale.

= ID-based header levels and scope resolution
{c}
{parent=h-parent-argument}

When mixing both \x[h-parent-argument] and \x[scope]{p}, things get a bit complicated, because when writing or parsing, we have to first determine the parent header before resolving scopes.

As a result, the follow simple rules are used:
* start from the last header of the highest level
* check if the `{parent=XXX}` is a suffix of its ID
* if not, proceed to the next smaller level, and so on, until a suffix is found

Following those rules for example, a file `tmp.ciro`:
``
= h1
{scope}

= h1 1
{parent=h1}
{scope}

= h1 1 1
{parent=h1-1}

= h1 1 2
{parent=h1-1}

= h1 1 3
{parent=h1/h1-1}

= h1 2
{parent=h1}
{scope}

= h1 2 1
{parent=h1-2}
{scope}

= h1 2 1 1
{parent=h1-2/h1-2-1}
``
will lead to the following header tree with \x[log-headers]:
``
= h1  tmp
== h2 1 tmp/h1-1
=== h3 1.1 tmp/h1-1/h1-1-1
=== h3 1.2 tmp/h1-1/h1-1-2
=== h3 1.3 tmp/h1-1/h1-1-3
== h2 2 tmp/h1-2
=== h3 2.1 tmp/h1-2/h1-2-1
==== h4 2.1.1 tmp/h1-2/h1-2-1/h1-2-1-1
``

= Header explicit levels vs nesting design choice
{parent=h-parent-argument}

Arguably, the language would be even saner if we did:
``
\H[My h1][

Paragraph.

\H[My h2][]
]
``
rather than having explicit levels as in `\H[1][My h1]` and so on.

But we chose not to do it like most markups available because it leads to too many nesting levels, and hard to determine where you are without tooling.

Ciro later "invented" (?) \x[h-parent-argument], which he feels reaches the perfect balance between the advantages of those two options.

= `\H` `scope` argument
{parent=h-arguments}

= Scope
{synonym}

In some use cases, the sections under a section describe inseparable parts of something.

For example, when documenting an experiment you executed, you will generally want an "Introduction", then a "Materials" section, and then a "Results" section for every experiment.

On their own, those sections don't make much sense: they are always referred to in the context of the given experiment.

The problem is then how to get unique IDs for those sections.

One solution, would be to manually add the experiment ID as prefix to every subsection, as in:
``
= Experiments

See: \x[full-and-unique-experiment-name/materials]

== Introduction

== Full and unique experiment name

=== Introduction
{id=full-and-unique-experiment-name/introduction}

See our awesome results: \x[full-and-unique-experiment-name/results]

For a more general introduction to all experiments, see: \x[introduction].

=== Materials
{id=full-and-unique-experiment-name/materials}

=== Results
{id=full-and-unique-experiment-name/results}
``

but this would be very tedious.

To keep those IDs shorter, Cirodown provides the `scope` \x[boolean-named-argument] property of \x[header]{p}, which works analogously to C++ namespaces with the header IDs.

Using `scope`, the previous example could be written more succinctly as:
``
= Experiments

See: \x[full-and-unique-experiment-name/materials]

== Introduction

== Full and unique experiment name
{scope}

=== Introduction

See our awesome results: \x[results]

For a more general introduction to all experiments, see: \x[/introduction].

=== Materials

=== Results
``

Note how:
* full IDs are automatically prefixed by the parent scopes prefixed and joined with a slash `/`
* we can refer to other IDs withing the current scope without duplicating the scope. E.g. `\x[results]` in the example already refers to the ID `full-and-unique-experiment-name/materials`
* to refer to an ID outside of the scope and avoid name conflicts with IDs inside of the current scope, we start a reference with a slash `/`

  So in the example above, `\x[/introduction]` refers to the ID `introduction`, and not `full-and-unique-experiment-name/introduction`.

When nested scopes are involved, \x[internal-cross-reference]{p} resolution peels off the scopes one by one trying to find the closes match, e.g. the following works as expected:
``
= h1
{scope}

== h2
{scope}

=== h3
{scope}

\x[h2]
``
Here Cirodown:
* first tries to loop for an `h1/h2/h3/h2`, since `h1/h2/h3` is the current scope, but that ID does not exist
* so it removes the `h3` from the current scope, and looks for `h1/h2/h2`, which is still not found
* then it removes the `h2`, leading to `h1/h2`, and that one is found, and therefore is taken

= Directory-based `scope`
{parent=h-scope-argument}

Putting files in subdirectories of the build has the same effect as adding a \x[scope] to their top level header.

Notably, all headers inside that directory get the directory prepended to their IDs.

The toplevel directory is determined as described at: \x[the-toplevel-index-file].

= Test scope 1
{parent=h-scope-argument}
{scope}

For fun and profit.

= Test scope 2
{parent=test-scope-1}
{scope}

Let's break this local link: \a[cirodown].

= Not scoped
{parent=test-scope-2}

= `\H` `scope` argument of toplevel headers
{parent=h-scope-argument}

When \x[the-toplevel-header] is given the `scope` property Cirodown automatically uses the file path for the scope and heaves fragments untouched.

For example, suppose that file `full-and-unique-experiment-name` contains:
``
= Full and unique experiment name
{scope}

== Introduction

== Materials
``

In this case, multi-file output will generate a file called `full-and-unique-experiment-name.html`, and the URL of the subsections will be just:
* `full-and-unique-experiment-name.html#introduction`
* `full-and-unique-experiment-name.html#materials`
instead of
* `full-and-unique-experiment-name.html#full-and-unique-experiment-name/introduction`
* `full-and-unique-experiment-name.html#full-and-unique-experiment-name/materials`

Some quick interactive cross file link tests:
* \x[not-readme-with-scope]
* \x[not-readme-with-scope/h2]
* \x[not-readme-with-scope/image-my-image]

= `\H` `splitDefault` argument
{parent=h-arguments}

When using \x[split-headers], \x[internal-cross-reference]{p} always point to non-split pages as mentioned at \x[internal-cross-reference-targets-in-split-headers].

If the `splitDefault` \x[boolean-named-argument] is given however:
* the split header becomes the default, e.g. `index.html` is now the split one, and `nosplit.html` is the non-split one
* the header it is given for, and all of its descendant headers will use the split header as the default internal cross target, unless the header is already rendered in the current page. This does not propagate across \x[include]{p} however.

For example, consider `README.ciro`:
``
= Toplevel
{splitDefault}

\x[h2][toplevel to h2]

\x[notreadme][toplevel to notreadme]

\Include[notreadme]

== h2
``
and `notreadme.ciro`:
``
= Notreadme

\x[h2][notreadme to h2]

\x[notreadme][notreadme to notreadme h2]

== Notreadme h2
``
Then the following links would be generated:
* `index.html`: split version of `README.ciro`, i.e. does not contain `h2`
  * `toplevel to h2`: `h2.html`. Links to the split version of `h2`, since `h2` is also affected by the `splitDefault` of its parent, and therefore links to it use the split version by default
  * `toplevel to notreadme`: `notreadme.html`. Links to non-split version of `notreadme.html` since that header is not `splitDefault`, because `splitDefault` does not propagate across includes
* `nosplit.html` non-split version of `README.ciro`, i.e. contains `h2`
  * `toplevel to h2`: `#h2`, because even though `h2` is `splitDefault`, that header is already present in the current page, so it would be pointless to reload the split one
  * `toplevel to notreadme`: `notreadme.html`
* `h2.html` split version of `h2` from `README.ciro`
* `notreadme.html`: non-split version of `notreadme.ciro`
  * `notreadme to h2`: `h2.html`, because `h2` is `splitDefault`
  * `notreadme to notreadme h2`: `#notreadme-h2`
* `notreadme-split.html`: split version of `notreadme.ciro`
  * `notreadme to h2`: `h2.html`, because `h2` is `splitDefault`
  * `notreadme to notreadme h2`: `notreadme.html#notreadme-h2`, because `notreadme-h2` is not `splitDefault`

The major application of this is that Ciro likes to work with a huge `README.ciro` containing thousands of random small topics. This is the case for example for: https://cirosantilli.com

And splitting those into separate source files would be quite laborious, as it would require duplicating IDs on the filename, and setting up \x[include]{p}.

However, after this README reaches a certain size, page loads start becoming annoyingly slow, even despite already loading large assets like \x[image]{p} video \x[video]{p} only on hover or click: the annoying slowness comes from the loading of the HTML itself before the browser can jump to the ID.

And even worse: this README corresponds to the main index page of the website, which will make what a large number of users will see be that slowness.

Therefore, once this README reaches a certain size, you can add the `splitDefault` attribute to it, to make things smoother for readers.

And if you have a smaller, more self-contained, and highly valuable tutorial such as https://cirosantilli.com/x86-paging[], you can just split that into a separate `.ciro` source file.

This way, any links into the smaller tutorial will show the entire page as generally desired.

And any links from the tutorial, back to the main massive README will link back to split versions, leading to fast loads.

This feature was implemented at: https://github.com/cirosantilli/cirodown/issues/131

= `\H` `splitSuffix` argument
{parent=h-arguments}

If given, add a custom suffix to the output filename of the header when using \x[split-headers].

If the given suffix is empty, it defaults to `-split`.

For example, given:
``
= my h1

== my h2
``
a `--split-headers` conversion would normally place `my h2` into a file called:
``
my-h2.html
``
However, if we instead wrote:
``
== my h2
{splitSuffix}
``
it would not be placed under:
``
my-h2-split.html
``
and if we set a custom one as:
``
== my h2
{splitSuffix=asdf}
``
it would go instead to:
``
my-h2-asdf.html
``

This option is useful if the root of your website is written in Cirodown, and you want to both:
* have a section that talks about some other project
* host the documentation of that project inside the project source tree

For example, https://cirosantilli.com with source at https://github.com/cirosantilli/cirosantilli.github.io has a quick section about Cirodown: https://cirosantilli.com#cirodown[].

Therefore, without a custom suffix, the split header version of that header would go to https://cirosantilli.com/cirodown[], which would collide with this documentation, that is present in a separate repository: https://github.com/cirosantilli/cirodown[].

Therefore a `splitSuffix` property is used, making the split header version fall under `/cirodown-split`, and leaving the nicer `/cirodown` for the more important project toplevel.

If given on the \x[the-toplevel-header]{p}, which normally gets a suffix by default to differentiate from the non-split version, it replaces the default `-split` suffix with a custom one.

For example if you had `notindex.ciro` as:
``
= Not index
``
then it would render to:
``
notindex-split.ciro
``
but if you used instead:
``
= Not index
{splitSuffix=asdf}
``
then it would instead be:
``
notindex-asdf.ciro
``

= `\H` `synonym` argument
{parent=h-arguments}

= Synonym
{synonym}

TODO implement: https://github.com/cirosantilli/cirodown/issues/114

This option is similar to \x[h-title2-argument] but it additionally:
* creates a new ID that you can refer to, and renders it with the alternate chosen title
* the rendered ID on \x[internal-cross-reference]{p} is the same as what it is a synonym for
* the synonym header is not rendered at all, including in the \x[table-of-contents]
* when using \x[split-headers], a redirect output file is generated from the synonym to the main ID. This is generally a superior redirection alternative to using \x[cirodown-json/redirects] from \x[cirodown-json]

Example:
``
= Parent

== GNU Debugger
{c}

= GDB
{c}
{synonym}

I like to say \x[gdb] because it is shorter than \x[gnu-debugger].
``
renders something like:
``
= GNU Debugger

I like to say \a[#gnu-debugger][GDB] because it is shorter than \x[#gnu-debugger][GNU Debugger].
``
Furthermore, if `--split-headers` is used, another file is generated:
``
gdb.html
``
which contains a redirection from `gdb.html` to `gnu-debugger.html`.

= `\H` `title2` argument of a synonym header
{parent=h-synonym-argument}

Unlike \x[h-title2-argument], the synonym does not show up by default next to the title. This is because we sometimes want that, and sometimes not. To make the title appear, you can simply add an empty `title2` argument to the synonym header as in:
``
= GNU Debugger
{c}

= GDB
{c}
{synonym}
{title2}

= Quantum computing

= Quantum computer
{synonym}
``
which renders something like:
``
= GNU Debugger (GDB)

= Quantum computing
``
Note how we added the synonym to the title only when it is not just a simple flexion variant, since `Quantum computing (Quantum computer)` would be kind of useless would be kind of useless.

= `\H` `title2` argument
{parent=h-arguments}

The `title2` argument can be given to any element that has the `title` argument.

Its usage is a bit like the `description=` argument of \x[image]{p}, allowing you to add some extra content to the header without affecting its ID.

Unlike `description=` however, `title2` shows up on all \x[x-full-argument][`full`] references, including appearances in the \x[table-of-contents], which make it more searchable.

Its primary use cases are:
* give acronyms, or other short names names of fuller titles such as mathematical/programming notation

  One primary reason to not use the acronyms as the main section name is to avoid possible ID ambiguities with other acronyms.
* give the header in different languages

For example, given the Cirodown input:
``
= Toplevel

The Toc follows:

== North Atlantic Treaty Organization
{c}
{title2=NATO}

\x[north-atlantic-treaty-organization]

\x[north-atlantic-treaty-organization]{full}
``
the rendered output looks like:
``
= Toplevel

The ToC follows:

* North Atlantic Treaty Organization (NATO)

== North Atlantic Treaty Organization (NATO)

North Atlantic Treaty Organization

Section 1. "North Atlantic Treaty Organization (NATO)"
``

Related alternatives to `title2` include:
* \x[h-disambiguate-argument] when you do want to affect the ID to remove ambiguities
* \x[h-synonym-argument]

Parenthesis are added automatically around all rendered `title2`.

The `title2` argument has a special meaning when applied to a \x[header] with the \x[h-synonym-argument], see \x[h-title2-argument-of-a-synonym-header].

= `\H` `wiki` argument
{parent=h-arguments}

If given, show a link to the Wikipedia article that corresponds to the header.

If a value is not given, automatically link to the Wiki page that matches the header exactly with spaces converted to underscores.

Here is an example with an explicit wiki argument:

``
==== Tiananmen Square
{wiki=Tiananmen_Square}
``

which looks like:

= Tiananmen Square
{id=wiki-explicit}
{parent=h-wiki-argument}
{wiki=Tiananmen_Square}

or equivalently with the value deduced from the title:

``
= Tiananmen Square
{wiki}
``

which looks like:

= Tiananmen Square
{id=wiki-implicit}
{parent=h-wiki-argument}
{wiki}

You can only link to subsections of wiki pages with explicit links as in:

``
= History or Tiananmen Square
{wiki=Tiananmen_Square#History}
``

which looks like:

= History or Tiananmen Square
{id=wiki-explicit-subsection}
{parent=h-wiki-argument}
{wiki=Tiananmen_Square#History}

= Image
{parent=macro}
{title2=`\Image` and `\image`}

A block image with \x[block-vs-inline-macros][capital] 'i' `Image` showcasing most of the image properties \x[image-my-test-image].
\CirodownExample[[
Have a look at this amazing image: \x[image-my-test-image].

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{title=The title of my image.}
{id=image-my-test-image}
{width=600}
{height=200}
{source=https://en.wikipedia.org/wiki/File:Tianasquare.jpg}
{description=The description of my image.}
]]
This exemplifies the following parameters:
* `description`: similar to `title`, but allow for further explanations without them appearing in \x[internal-cross-reference][cross references] to the image
* `source`: a standardized way to credit an image by linking to a URL that contains further image metadata
For further discussion on the effects of ID see: \x[image-id][full].

And this is how you make an inline image inline one with lower case `i`:
\CirodownExample[[
My inline \image[Tank_man_standing_in_front_of_some_tanks.jpg][test image] is awesome.
]]
Inline images can't have captions.

The `description` can have multiple paragraphs just like any other element, but we don't recommend this style because it makes it hard for readers to see what is part of the image caption and what is part of the next paragraph.
\CirodownExample[[
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{id=image-my-test-image-description-paragraphs}
{title=The title of my image.}
{source=https://en.wikipedia.org/wiki/File:Tianasquare.jpg}
{description=Description paragraph 1.

Description paragraph 2.
}

Paragraph after.
]]
Maybe we could improve this with some CSS styling, but generally when you want multiple paragraphs inside the image, you might instead be better off making an \x[internal-cross-file-reference]{p} to the image and adding your extended explanation outside.

And now an image outside of \x[cirodownexample] to test how it looks directly under \x[toplevel]:

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{id=image-my-test-image-toplevel}

= Image height
{parent=image}

By default, we fix image heights to `height=315`, and let the `width` be calculated proportionally once the image loads. We therefore ignore the actual image size. This is done to:
* prevent reflows as the page loads images and can determine their actual sizes, especially is the user opens the page at a given ID in the middle of the page
* create a more uniform media experience by default, unless a custom image size is actually needed e.g. if the image needs to be larger

= Image IDs and captions
{id=image-id}
{parent=image}

Here is an image without a description but with an ID so we can link to it: \x[image-my-test-image-2].
\CirodownExample[[
Have a look at this amazing image: \x[image-my-test-image-2].

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{id=image-my-test-image-2}
]]
This works because \x[x-full-argument][`full` is the default cross reference style for `Image`], otherwise the link text would be empty since there is no `title`, and cirodown would raise an error.

Cirodown can optionally deduce the title from the basename of the `src` argument if the `titleFromSrc` \x[boolean-named-argument] is given, or if `title-from-src` is set as the default \x[cirodown-json/media-providers][media provider] for the media type:
\CirodownExample[[
Have a look at this amazing image: \x[image-tank-man-standing-in-front-of-some-tanks].

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{titleFromSrc}
]]

If the image has neither ID nor title, then it does not get a caption at all, and it is not possible to link to it with an \x[internal-cross-reference], e.g.:
\CirodownExample[[
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
]]
The image does however get an automatically generated ID based on its image number, and it is possible for readers to link to that ID on the rendered version, e.g. as:
``
#image-123
``
This link is of course not stable across document revisions however, since if an image is added before that one, the link will break. This kind of image is discouraged, because in paged output formats like PDF, it could float away from the text that refers to the image.

We can also see that such an image does not increment the Figure count:
\CirodownExample[[
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]{id=image-my-test-image-count-before}
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]{id=image-my-test-image-count-after}
]]

If the image has any visible metadata such as `source` or `description` however, then the caption does show and the Figure count gets incremented:
\CirodownExample[[
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]{source=https://en.wikipedia.org/wiki/File:Tianasquare.jpg}
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]{description=This is the description of my image.}
]]

= Where to store images
{parent=image}

= Store images inside the repository itself
{parent=where-to-store-images}

If you are making a limited repository that will not have a ton of images, then you can get away with simply git tracking your images in the main repository.

With this setup, no further action is needed. For example, with a file structure of:
``
./README.ciro
./Tank_man_standing_in_front_of_some_tanks.jpg
``
just use the image from \C[README.ciro] as:
\CirodownExample[[
\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
]]

However, if you are making a huge tutorial, which can have a huge undefined number of images (i.e. any scientific book), then you likely don't want to git track your images in the git repository.

= Store images in a separate media repository
{parent=where-to-store-images}

In this approach, you create a separate GitHub repository in addition to the main one containing the text to contain only media such as images.

This approach is more suitable than \x[store-images-inside-the-repository-itself] if you are going to have a lot of images.

When using this approach, you could of course just point directly to the final image URL, e.g. as in:
\CirodownExample[[
\Image[https://raw.githubusercontent.com/cirosantilli/media/master/Chrysanthemum_Xi_Jinping_with_black_red_liusi_added_by_Ciro_Santilli.jpg]
]]
but Cirodown allows you use configurations that allow you to enter just the image basename: `Chrysanthemum_Xi_Jinping_with_black_red_liusi_added_by_Ciro_Santilli.jpg` which we will cover next.

In order to get this to work, the recommended repository setup is:
* `./main-repo/.git`: main repository at https://github.com/username/main-repo
* `./main-repo/data/media/.git/`: media repository at https://github.com/username/main-repo-media[], and where `data/` is gitignored.
The directory and repository names are not mandatory, but if you place media in `data/media` and name its repository by adding the `*-media` suffix, then `cirodown` will handle everything for you without any further configuration in \x[cirodown-json/media-providers].

This particular documentation repository does have a different setup as can be seen from its \a[cirodown.json]. Then, when everything is setup correctly, we can refer to images simply as:
\CirodownExample[[
\Image[Chrysanthemum_Xi_Jinping_with_black_red_liusi_added_by_Ciro_Santilli.jpg]{provider=github}
]]
In this example, we also needed to set `{provider=github}` explicitly since it was not set as the default image provider in our `cirodown.json`. In most projects however, all of your images will be in the default repository, so this won't be needed.

`provider` must not be given when a full URL is given because we automatically detect providers from URLs, e.g.:
``
\Image[https://raw.githubusercontent.com/cirosantilli/media/master/Chrysanthemum_Xi_Jinping_with_black_red_liusi_added_by_Ciro_Santilli.jpg]{provider=github}
``
is an error.

TODO implement: `cirodown` will even automatically add and push used images in the `my-tutorial-media` repository for you \x[publish][during publishing]!

You should then use the following rules inside `my-tutorial-media`:
* give every file a very descriptive and unique name as a full English sentence
* never ever delete any files, nor change their content, unless it is an improvement in format that does change the information contained of the image TODO link to nice Wikimedia Commons guideline page
This way, even though the repositories are not fully in sync, anyone who clones the latest version of the `*-media` directory will be able to view any version of the main repository.

Then, if one day the media repository ever blows up GitHub's limit, you can just migrate the images to another image server that allows arbitrary basenames, e.g. AWS, and just configure your project to use that new media base URL with the \x[cirodown-json/media-providers] option.

The reason why images should be kept in a separate repository is that images are hundreds or thousands of times larger than hand written text.

Therefore, images could easily fill up the maximum repository size you are allowed: https://webapps.stackexchange.com/questions/45254/file-size-and-storage-limits-on-github#84746 and then what will you do when GitHub comes asking you to reduce the repository size?

https://git-lfs.github.com/[Git LFS] is one approach to deal with this, but we feel that it adds too much development overhead.

= Store images in Wikimedia Commons
{parent=where-to-store-images}

Wikimedia Commons is another great possibility to upload your images to:
\CirodownExample[[
\Image[https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Gel_electrophoresis_insert_comb.jpg/450px-Gel_electrophoresis_insert_comb.jpg]
{source=https://commons.wikimedia.org/wiki/File:Gel_electrophoresis_insert_comb.jpg}
]]

Cirodown likes Wikimedia Commons so much that we automatically parse the image URL and if it is from Wikimedia Commons, automatically deduce the `source` for you. So the above image renders the same without the `source` argument:
\CirodownExample[[
\Image[https://upload.wikimedia.org/wikipedia/commons/5/5b/Gel_electrophoresis_insert_comb.jpg]
]]

And like for non-Wikimedia images, you can automatically generate a `title` from the `src` by setting the `titleFromSrc` \x[boolean-named-argument] or if `title-from-src` is set as the default \x[cirodown-json/media-providers][media provider] for the media type:
\CirodownExample[[
\Image[https://upload.wikimedia.org/wikipedia/commons/5/5b/Gel_electrophoresis_insert_comb.jpg]
{titleFromSrc}
]]

And a quick test for a more complex thumb resized URL:
\CirodownExample[[
\Image[https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/Gel_electrophoresis_insert_comb.jpg/450px-Gel_electrophoresis_insert_comb.jpg]
]]

If you really absolutely want to turn off the `source`, you can explicitly set:
\CirodownExample[[
\Image[https://upload.wikimedia.org/wikipedia/commons/5/5b/Gel_electrophoresis_insert_comb.jpg]
{source=}
]]
but you don't want to do that for the most commonly Wikimedia Commons used license of CC BY+, do you? :-)

Upsides of using Wikimedia Commons for your images:
* makes it easier for other writers to find and reuse your images
* automatically generates resized versions of the uploaded images into several common dimensions so you can pick the smallest one that fits your desired \x[image-height] to reduce bandwidth usage
* if you have so many images that they would blow even the size of a \x[store-images-in-a-separate-media-repository][separate media repository], this will still work
Downsides:
* forces you to use the Creative Commons license
* requires the content to be educational in nature
* uploading a bunch of images to Wikimedia Commons does feel a bit more laborious than it should because you have to write down so much repeated metadata for them

= Image lazy loading
{parent=image}

We do this by default because Cirodown is meant to allow producing huge single page documents like Ciro likes it, and in this way:
* images that the user is looking at will load first
* we save a lot of bandwidth for the user who only wants to browse one section

TODO: maybe create a mechanism to disable this for the entire build with \x[cirodown-json].

= Background color of transparent images
{parent=image}

For the love of God, there is no standardized for SVG to set its background color without a rectangle? https://stackoverflow.com/questions/11293026/default-background-color-of-svg-root-element `viewport-fill` was just left in limbo?

And as a result, many many many SVG online images that you might want to reuse just rely on white pages and don't add that background rectangle.

Therefore for now we just force white background on \x[overview-of-files-in-this-repository][our default CSS], which is what most SVGs will work with. Otherwise, you can lose the entire image to our default black background.

Then if someone ever has an SVG that needs another background color, we can add an image attribute to set that color as a local style.

= Image generators
{parent=image}

TODO implement: mechanism where you enter a textual description of the image inside the code body, and it then converts to an image, adds to the `-media` repo and pushes all automatically. Start with dot.

https://github.com/cirosantilli/cirodown/issues/40

= Include
{title2=`\Include`}
{parent=macro}

The `\Include` macro allows including an external Cirodown headers under the current header.

It exists to allow optional single page HTML output while still retaining the ability to:
* split up large input files into multiple files to make renders faster during document development
* suggest an optional custom output split with one HTML output per Cirodown input, in order to avoid extremely large HTML pages which could be slow to load

`\Include` takes one mandatory argument: the ID of the section to be included, much like \x[internal-cross-reference]{p}.

There is however one restriction: only \x[the-toplevel-header]{p} can be pointed to. This restriction allows us to easily find the included file in the filesystem, and dispenses the need to do a first `./cirodown` run to generate the \x[internal-cross-file-reference-internals][ID database]. This works because \x[the-id-of-the-first-header-is-derived-from-the-filename].

Headers of the included document are automatically shifted to match the level of the child of the level where they are being included.

If \x[embed-includes] is given, the external document is rendered embedded into the current document directly, essentially as if the source had been copy pasted (except for small corrections such as the header offsets).

Otherwise, the following effects happen:
* The headers of the included tree appear in the \x[table-of-contents] of the document as links to the corresponding external files.

  This is implemented simply by reading a previously generated database file much like \x[internal-cross-file-reference-internals], which avoids the slowdown of parsing all included files every time.

  As a result, you have to do an initial parse of all files in the project to extract their headers however, just as you would need to do when linking to those headers.
* the include itself renders as a link to the included document
* \x[embed-includes]

Here is an example of inclusion of the files `not-readme.ciro` and `not-readme-2.ciro`:
``
\Include[not-readme]
\Include[not-readme-2]
\Include[not-readme-with-scope]
``
The above is the recommended and slightly \x[insane-macro-shortcuts][insaner] version of:
``
\Include[not-readme]

\Include[not-readme-2]

\Include[not-readme-with-scope]
``
The insaner version is a bit insaner because the `\Include` magically discards the following newline node that follows it if it just a plaintext node containing exactly a newline. With a double newline, the newline would already have been previously taken out on the lexing stage as part of a paragraph.

\x[include-example]{full} shows what those actually render like.

= `\Include` `parent` argument
{parent=include}

This option is analogous to \x[h-parent-argument], but for \x[include]{p}.

For example, consider you have:
``
= Animal

== Dog

== Cat

== Bat
``
and now you want to split `Cat` to `cat.ciro`.

If you wrote:
``
= Animal

== Dog

\Include[cat]

== Bat
``
Cat would be a child of Dog, since that is the previous header, which is not what we want.

Instead, we want to write:
``
= Animal

== Dog

\Include[cat]{parent=animal}

== Bat
``
and now Cat will be a child of Animal as desired.

Implemented at: https://github.com/cirosantilli/cirodown/issues/127

= `\Include` example
{parent=include}

This shows what includes render as.

\Include[not-readme]
\Include[not-readme-2]
\Include[not-readme-with-scope]
\Include[subdir]
\Include[subdir/notindex]

= Italic
{parent=macro}
{title2=`\i`}

\CirodownExample[[
Some \i[italic] text.
]]

= `\JsCanvasDemo`
{parent=macro}

The `JsCanvasDemo` macro allows you to create interactive HTML/JavaScript https://en.wikipedia.org/wiki/Canvas_element[canvas] demos easily.

These demos:
* only start running when the user scrolls over them for the first time
* stop automatically when they leave the viewport
so you can stuff as many of them as you want on a page, and they won't cause the reader's CPU to fry an egg.

\CirodownExample[[[
\JsCanvasDemo[[
new class extends CirodownCanvasDemo {
  init() {
    super.init('hello');
    this.pixel_size_input = this.addInputAfterEnable(
      'Pixel size',
      {
        'min': 1,
        'type': 'number',
        'value': 1,
      }
    );
  }
  draw() {
    var pixel_size = parseInt(this.pixel_size_input.value);
    for (var x = 0; x < this.width; x += pixel_size) {
      for (var y = 0; y < this.height; y += pixel_size) {
        var b = ((1.0 + Math.sin(this.time * Math.PI / 16)) / 2.0);
        this.ctx.fillStyle =
          'rgba(' +
          (x / this.width) * 255 + ',' +
          (y / this.height) * 255 + ',' +
          b * 255 +
          ',255)'
        ;
        this.ctx.fillRect(x, y, pixel_size, pixel_size);
      }
    }
  }
}
]]
]]]

And another one showing off some https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API[WebGL]:

\JsCanvasDemo[[
new class extends CirodownCanvasDemo {
  init() {
    super.init('webgl', {context_type: 'webgl'});
    this.ctx.viewport(0, 0, this.ctx.drawingBufferWidth, this.ctx.drawingBufferHeight);
    this.ctx.clearColor(0.0, 0.0, 0.0, 1.0);
    this.vertexShaderSource = `
#version 100
precision highp float;
attribute float position;
void main() {
  gl_Position = vec4(position, 0.0, 0.0, 1.0);
  gl_PointSize = 64.0;
}
`;

    this.fragmentShaderSource = `
#version 100
precision mediump float;
void main() {
  gl_FragColor = vec4(0.18, 0.0, 0.34, 1.0);
}
`;
    this.vertexShader = this.ctx.createShader(this.ctx.VERTEX_SHADER);
    this.ctx.shaderSource(this.vertexShader, this.vertexShaderSource);
    this.ctx.compileShader(this.vertexShader);
    this.fragmentShader = this.ctx.createShader(this.ctx.FRAGMENT_SHADER);
    this.ctx.shaderSource(this.fragmentShader, this.fragmentShaderSource);
    this.ctx.compileShader(this.fragmentShader);
    this.program = this.ctx.createProgram();
    this.ctx.attachShader(this.program, this.vertexShader);
    this.ctx.attachShader(this.program, this.fragmentShader);
    this.ctx.linkProgram(this.program);
    this.ctx.detachShader(this.program, this.vertexShader);
    this.ctx.detachShader(this.program, this.fragmentShader);
    this.ctx.deleteShader(this.vertexShader);
    this.ctx.deleteShader(this.fragmentShader);
    if (!this.ctx.getProgramParameter(this.program, this.ctx.LINK_STATUS)) {
      console.log('error ' + this.ctx.getProgramInfoLog(this.program));
      return;
    }
    this.ctx.enableVertexAttribArray(0);
    var buffer = this.ctx.createBuffer();
    this.ctx.bindBuffer(this.ctx.ARRAY_BUFFER, buffer);
    this.ctx.vertexAttribPointer(0, 1, this.ctx.FLOAT, false, 0, 0);
    this.ctx.useProgram(this.program);
  }
  draw() {
    this.ctx.clear(this.ctx.COLOR_BUFFER_BIT);
    this.ctx.bufferData(this.ctx.ARRAY_BUFFER, new Float32Array([Math.sin(this.time / 60.0)]), this.ctx.STATIC_DRAW);
    this.ctx.drawArrays(this.ctx.POINTS, 0, 1);
  }
}
]]

= List
{parent=macro}
{title2=`* `, `\L`, `\Ul`, `\Ol`}

\x[insane-macro-shortcuts][Insane] with `* ` (asterisk space):
\CirodownExample[[
* a
* b
* c
]]

Equivalent saner with \x[auto-parent][implicit `ul` container]:
\CirodownExample[[
\L[a]
\L[b]
\L[c]
]]

Equivalent fully sane with explicit container:
\CirodownExample[[
\Ul[
\L[a]
\L[b]
\L[c]
]
]]

The explicit container is required if you want to pass extra arguments properties to the `ul` list macro, e.g. a title and an ID: \x[list-my-id]{full}:
\CirodownExample[[
\Ul
{id=list-my-id}
[
\L[a]
\L[b]
\L[c]
]
]]
This is the case because without the explicit container in an implicit `ul` list, the arguments would stick to the last list item instead of the list itself.

It is also required if you want ordered lists:
\CirodownExample[[
\Ol[
\L[first]
\L[second]
\L[third]
]
]]

Insane nested list with two space indentation:
\CirodownExample[[
* a
  * a1
  * a2
  * a2
* b
* c
]]
The indentation must always be exactly equal to two spaces, anything else leads to errors or unintended output.

Equivalent saner nested lists with implicit containers:
\CirodownExample[[
\L[
a
\L[a1]
\L[a2]
\L[a2]
]
\L[b]
\L[c]
]]

Insane list item with a paragraph inside of it:
\CirodownExample[[
* a
* I have

  Multiple paragraphs.

  * And
  * also
  * a
  * list
* c
]]

Equivalent sane version:
\CirodownExample[[
\L[a]
\L[
I have

Multiple paragraphs.

\L[And]
\L[also]
\L[a]
\L[list]
]
\L[c]
]]

Insane lists may be escaped with a backslash as usual:
\CirodownExample[[
\* paragraph starting with an asterisk.
]]

And now a list outside of \x[cirodownexample] to test how it looks directly under \x[toplevel]:

\L[a]
\L[b]
\L[c]

= Mathematics
{parent=macro}
{title2=`$$`, `$`, `\M`, `\m`}

Via https://katex.org/[KaTeX] server side, oh yes!

Inline math is done with the dollar sign (`$`) \x[insane-macro-shortcuts][insane macro shortcut]:
\CirodownExample[[
My inline $\sqrt{1 + 1}$ is awesome.
]]
and block math is done with two or more dollar signs (`$$`):
\CirodownExample[[
$$
\sqrt{1 + 1} \\
\sqrt{1 + 1}
$$
]]

The sane version of inline math is a lower case `m`:
\CirodownExample[[[
My inline \m[[\sqrt{1 + 1}]] is awesome.
]]]
and the sane version of block math is with an upper case `M`:
\CirodownExample[[[
\M[[
\sqrt{1 + 1} \\
\sqrt{1 + 1}
]]
]]]

The capital vs lower case theme is also used in other elements, see: \x[block-vs-inline-macros].

In the sane syntax, \x[escape-characters][as with any other argument], you have to either escape any closing square brackets `]` with a backslash `\`:
\CirodownExample[[
My inline \m[1 - \[1 + 1\] = -1] is awesome.
]]
or with the equivalent double open and close:
``
My inline \m[[1 - [1 + 1] = -1]] is awesome.
``

HTML escaping happens as you would expect, e.g. < shows fine in:
\CirodownExample[[
$$
1 < 2
$$
]]

Equation IDs and titles and linking to equations works identically to \x[image]{p}, see that section for full details. Here is one equation reference example that links to the following insane syntax equation: \x[equation-my-first-insane-equation]:
\CirodownExample[[
$$
\sqrt{1 + 1}
$$
{title=My first insane equation.}
]]
and the sane equivalent \x[equation-my-first-sane-equation]:
\CirodownExample[[[
\M{title=My first sane equation.}[[
\sqrt{1 + 1}
]]
]]]

Here is a raw one just to test the formatting outside of a `cirodown_comment`:
$$\sqrt{1 + 1}$$

= Math defines across blocks
{parent=mathematics}

First here is an invisible block (with `{show=0}`) defining with a `\newcommand` definition after this paragraph:
\CirodownExample[[
$$
\newcommand{\foo}[0]{bar}
$${show=0}
]]
We make it invisible because this block only contains KaTeX definitions, and should not render to anything.

Then the second math block uses those definitions:
\CirodownExample[[
$$
\foo
$$
]]

Analogously with `\def`, definition:
\CirodownExample[[
$$
\gdef\foogdef{bar}
$${show=0}
]]
and the second block using it:
\CirodownExample[[
$$
\foogdef
$$
]]

And just to test that `{show=1}` actually shows, although it is useless, and that `{show=0}` skips incrementing the equation count:
\CirodownExample[[
$$1 + 1$${show=1}
$$2 + 2$${show=0}
$$3 + 3$${show=1}
]]

= `cirodown.tex`
{parent=mathematics}

If your project has multiple `.ciro` input files, you can share Mathematics definitions across all files by adding them to the `cirodown.tex` file on the toplevel directory.

For example, if `cirodown.tex` contains:
``
\newcommand{\foo}[0]{bar}
``
then from any `.ciro` file we in the project can use:
``
$$
\foo
$$
``

= Paragraph
{title2=`\P`}
{parent=macro}

OK, this is too common, so we opted for some \x[insane-macro-shortcuts][insanity] here: double newline is a paragraph!
\CirodownExample[[
Paragraph 1.

Paragraph 2.
]]

Equivalently however, you can use an explicit `\P` macros as well, which is required for example to add properties to a paragraph, e.g.:
\CirodownExample[[
\P{id=paragraph-1}[Paragraph 1]
\P{id=paragraph-2}[Paragraph 2]
]]

Paragraphs are created automatically inside \x[macro-argument-syntax][macro argument] whenever a double newline appears.

Note that Cirodown paragraphs render in HTML as `div` with `class="p"` and not as `p`. This means that you can add basically anything inside them, e.g. a list:
``
My favorite list is:
\Ul[
\li[aa]
\li[bb]
]
because it is simple.
``
which renders as a single paragraph.

One major advantage of this, is that when writing documentation, you often want to keep lists or code blocks inside a given paragraph, so that it is easy to reference the entire paragraph with an ID. Think for example of paragraphs in the C++ standard.

= Passthrough
{parent=macro}
{title2=`\passthrough`}

Dumps its contents directly into the rendered output.

This construct is not XSS safe, see: \x[unsafe-xss]{full}.

Here for example we define a paragraph in raw HTML:
\CirodownExample[[[
\passthrough[[
<p>Hello <b>raw</b> HTML!</p>
]]
]]]

And for an inline passthrough:
\CirodownExample[[[
Hello \passthrough[[<b>raw</b>]] world!
]]]

= Quotation
{parent=macro}
{title2=`\Q`}

With `q`:
\CirodownExample[[
And so he said:

\Q[
Something very smart

And with multiple paragraphs.
]

and it was great.
]]

= Table
{parent=macro}
{title2=`|| `, `| `, `\Table`, `\Tr`, `\Th` and `\Td`}

The \x[insane-code-and-math-shortcuts][insane] syntax marks:
* headers with `|| ` (pipe, pipe space) at the start of a line
* regular cells with `| ` (pipe, space) at the start of a line
* separates rows with double newline
For example:
\CirodownExample[[
|| Header 1
|| Header 2

| 1 1
| 1 2

| 2 1
| 2 2
]]
Empty cells are allowed without the trailing space however:
\CirodownExample[[
| 1 1
|
| 1 3

| 2 1
|
| 2 3
]]

Equivalent fully explicit version:
\CirodownExample[[
\Table[
\Tr[
  \Th[Header 1]
  \Th[Header 2]
]
\Tr[
  \Td[1 1]
  \Td[1 2]
]
\Tr[
  \Td[2 1]
  \Td[2 2]
]
]
]]
Any white space indentation inside an explicit `\Tr` can make the code more readable, and is automatically removed from final output due to \x[remove-whitespace-children] which is set for `\Table`.

To pass further arguments to an implicit table such as `title` or `id`, you need to use an explicit `table` macro as in: \x[table-my-table].
\CirodownExample[[
\Table
{title=My table title.}
{id=table-my-table}
[
|| Header 1
|| Header 2

| 1 1
| 1 2

| 2 1
| 2 2
]
]]
The rules of when the caption shows up or not are the same as described for \x[image]{p}.

Multiple source lines, including paragraphs, can be added to a single cell with insane syntax by indenting the cell with exactly two spaces just as for \x[list]{p}, e.g.:
\CirodownExample[[
|| h1
|| h2
|| h3

  h3 2

| 11
| 12

  12 2
| 13

| 21
| 22
| 23
]]
Arbitrarily complex nested constructs may be used, e.g. a table inside a list inside table:
\CirodownExample[[
| 00
| 01

  * l1
  * l2

    | 20
    | 21

    | 30
    | 31

| 10
| 11
]]

And now a table outside of \x[cirodownexample] to test how it looks directly under \x[toplevel]:

\Table{title=My table title.}
[
\Tr[
  \Th[Header 1]
  \Th[Header 2]
]
\Tr[
  \Td[1 1]
  \Td[1 2]
]
\Tr[
  \Td[2 1]
  \Td[2 2]
]
]

And a fully insane one:

|| Header 1
|| Header 2

| 1 1
| 1 2

| 2 1
| 2 2

= Table sorting
{parent=table}

JavaScript interactive on-click table sorting is enabled by default, try it out by clicking on the header row:
\CirodownExample[[
|| String col
|| Integer col
|| Float col

| ab
| 2
| 10.1

| a
| 10
| 10.2

| c
| 2
| 3.4
]]
Powered by: https://github.com/tristen/tablesort

= Table of contents
{parent=macro}
{title2=`\Toc`}

Cirodown automatically adds a ToC at the end of the first \x[the-toplevel-header][non-toplevel header] of every document.

For example, on a standard document with a single toplevel header:
``
= Animal

Animals are cute!

== Dog

== Cat
``
the ToC is rendered like:
``
= Animal

Animals are cute!

Table of Contents
* Dog
* Cat

== Dog

== Cat
``

You may customize ToC placement with `\Toc` macro, but just don't do it, it will just go against common convention and confuse readers.

This is especially important when considering \x[split-headers], where you almost always want an automatically generated ToC for every split header, otherwise you would need to add them all manually.

Only one ToC is rendered per document. Any ToC besides the first one is ignored. In particular, this means that \x[include]{p} with \x[embed-includes] work seamlessly and render a single table of contents, even if multiple `\Toc` macros are present in the included pages.

The \x[internal-cross-reference][ID] of the ToC is always fixed to `#toc`. If you try to use that for another element, you will get the following error:
``
error: tmp.ciro:3:1: reserved ID "toc"
``

The ToC ignores \x[the-toplevel-header] if you have one.

For when you want a quick outline of the header tree on the terminal, also consider the \x[log-headers] option.

= Table of contents JavaScript open close interaction
{parent=table-of-contents}

To the left of table of content entries you can click on an open/close icon to toggle the visibility of different levels of the table of contents.

The expansion algorithm is optimized so that when you first click on the arrow of a node it will give you an overview of that node, showing only its direct children.

At the start, all nodes are showing, to facilitate Ctrl + F queries, and so when you first click on a node, it collapses the children of children, so you can see only the direct children the node of interest, without getting a gazillion of sub descendants shown first.

The exact behaviour is:
* if a node is open:
  * if all children are closed, close the element, This can improve the view of its siblings. The toplevel "Table of Contents" node never closes however, since we never want to close that one.
  * otherwise, close all children. This Gives a good overview of the children, without any children of children getting in the way.
* if a node is closed (not showing children), open it and show all children and their descendants.

As a result of the above rules, clicking on a node three times goes through a loop of basically all useful states:
* node open and children open (initial state
* node open and children closed
* node closed

Clicking on the link from a \x[header] up to the table of contents also automatically opens up the node for you in case it had been previously closed manually.

= Video
{parent=macro}
{title2=`\Video` and `\video`}

Very analogous to \x[image]{p}, only differences will be documented here.

In the case of videos, \x[where-to-store-images] becomes even more critical since videos are even larger than images, such that the following storage approaches are impractical off the bat:
* \x[store-images-inside-the-repository-itself]
* \x[store-images-in-a-separate-media-repository]
As a result, then https://commons.wikimedia.org[Wikimedia Commons] is one of the best options \x[store-images-in-wikimedia-commons][much like for images]:
\CirodownExample[[
\Video[https://upload.wikimedia.org/wikipedia/commons/8/85/Vacuum_pump_filter_cut_and_place_in_eppendorf.webm]
{id=sample-video-in-wikimedia-commons}
{title=Nice sample video stored in Wikimedia Commons.}
{start=5}
]]
We also handle more complex transcoded video URLs just fine:
\CirodownExample[[
\Video[https://upload.wikimedia.org/wikipedia/commons/transcoded/1/19/Scientific_Industries_Inc_Vortex-Genie_2_running.ogv/Scientific_Industries_Inc_Vortex-Genie_2_running.ogv.480p.vp9.webm]
{id=sample-video-in-wikimedia-commons-transcoded}
{title=Nice sample video stored in Wikimedia Commons transcoded.}
]]
Commons is better than YouTube if your content is on-topic there because:
* they have no ads
* it allows download of the videos: https://www.quora.com/Can-I-download-Creative-Commons-licensed-YouTube-videos-to-edit-them-and-use-them[].
* it makes it easier for other users to find and re-use your videos

If your video does not fit the above Wikimedia Commons requirements, YouTube could be a good bet. Cirodown https://github.com/cirosantilli/cirodown/issues/50[automatically detects YouTube URLs] for you, so the following should just work:
\CirodownExample[[
\Video[https://youtube.com/watch?v=YeFzeNAHEhU&t=38]
{id=sample-video-from-youtube-implicit-youtube}
{title=Nice sample video embedded from YouTube implicit from `youtube.com` URL.}
]]
The `youtu.be` domain hack URLs also work;
\CirodownExample[[
\Video[https://youtu.be/YeFzeNAHEhU?t=38]
{id=sample-video-from-youtube-implicit-youtu-be}
{title=Nice sample video embedded from YouTube implicit from `youtu.be` URL.}
]]
Alternatively, you can reach the same result in a more explicit and minimal way by setting `{provider=youtube}` and the \x[video-start-argument][`start`] arguments:
\CirodownExample[[
\Video[YeFzeNAHEhU]{provider=youtube}
{id=sample-video-from-youtube-explicit}
{title=Nice sample video embedded from YouTube with explicit `youtube` argument.}
{start=38}
]]
When the `youtube` provider is selected, the Video address should only to contain the YouTube video ID, which shows in the YouTube URL for the video as:
``
https://www.youtube.com/watch?v=<video-id>
``
Remember that you can also enable the `youtube` provider by default on your \x[cirodown-json] with:
``
"media-provider" {
  "youtube": {"default-for": "video"}
}
``

But you can also use raw video files from any location that can serve them of course, e.g. here is one stored in this repository: \x[sample-video-in-repository].
\CirodownExample[[
\Video[Tank_man_side_hopping_in_front_of_some_tanks.mp4]
{id=sample-video-in-repository}
{title=Nice sample video stored in this repository.}
{source=https://www.youtube.com/watch?v=YeFzeNAHEhU}
{start=3}
]]

And as for images, setting `titleFromSrc` automatically calculates a title for you:
\CirodownExample[[
\Video[Tank_man_side_hopping_in_front_of_some_tanks.mp4]
{titleFromSrc}
{source=https://www.youtube.com/watch?v=YeFzeNAHEhU}
]]

= Video lazy loading
{parent=video}

Unlike \x[image-lazy-loading], we don't support video lazy loading yet because:
* non-`youtube` videos use the `video` tag which has no `loading` property yet
* `youtube` videos are embedded with `iframe` and `iframe` has no `loading` property yet

Both of this cases could be worked around with JavaScript:
* non-`youtube`: set `src` from JavaScript as shown for images: https://stackoverflow.com/questions/2321907/how-do-you-make-images-load-lazily-only-when-they-are-in-the-viewport/57389607#57389607[].

  But this breaks page semantics however, we don't know how to work around that
* `youtube` videos: same as above for the `iframe`, but this should be less problematic since YouTube videos are not viewable without JavaScript anyways, and who cares about `iframe` semantics?

= `\Video` `start` argument
{parent=video}

The time to start playing the video at in seconds. Works for both `youtube` and non-YouTube videos.

= Internal cross reference
{parent=macro}
{title2=`\x`}

Every macro in Cirodown can have an optional `id` and many also have a reserved `title` property.

When a macro in the document has a `title` argument but no `id` argument given, get an auto-generated ID from the title: \x[automatic-id-from-title].

For macros that do have an ID, derived from `title` or not, you can write a cross reference to it, e.g.:
\CirodownExample[[
See this \x[internal-cross-reference]{p} awesome section.
]]

An explicit link body can be given just as for regular HTTP \x[link]{p} as:
\CirodownExample[[
See this \x[internal-cross-reference]{p}[awesome section].
]]

= Cross reference title inflection
{parent=internal-cross-reference}

A common usage pattern is that we want to use \x[header] titles in \x[x-full-argument][non-full] \x[internal-cross-reference]{p} as the definition of a concept without repeating the title, for example:
``
== Dog

Cute animal.

\x[cats][Cats] are its natural enemies.

== Cats

This is the natural enemy of a \x[dog][dog].

\x[dog][Dogs] are cute, but they are still the enemy.

One example of a cat is \x[felix-the-cat].

=== Felix the Cat

Felix is not really a \x[cats][cat], just a carton character.
``

However, word https://en.wikipedia.org/wiki/Inflection[inflection] makes it much harder to avoid retyping the definition again.

For example, in the previous example, without any further intelligent behaviour we would be forced to re-type `\x[dog][dog]` instead of the desired `\x[dog]`.

Cirodown can take care of some inflection cases for you.

For capitalization, both headers and cross reference macros have the `c` \x[boolean-named-argument] which stands for "capitalized":
* for headers, `c` means that the header title has fixed capitalization as given in the title, i.e.
  * if the title has a capital first character, it will always show as a capital, as is the case for most https://en.wikipedia.org/wiki/Proper_noun[proper noun]
  * if it is lower case, it will also always remain lower case, as is the case for some rare proper nouns, notably https://en.wikipedia.org/wiki/Arm_Holdings[the name of certain companies]

  This means that for such headers, `c` in the `x` has no effect. Maybe we should give an error in that case. But lazy now, send PR.
* for cross reference macros, `c` means that the first letter of the title should be capitalized.

  Using this option is required when you are starting a sentence with a non-proper noun.
Capitalization is handled by a \x[javascript-case-conversion].

For pluralization, cross reference macros have the `p` \x[boolean-named-argument] which stands for "pluralize":
* if given and true, this automatically pluralizes the last word of the target title by using the https://github.com/blakeembrey/pluralize library
* if given and false, automatically singularize
* if not given, don't change the number of elements
If your desired pluralization is any more complex than modifying the last word of the title, you must do it manually however.

With those rules in mind, the previous Cirodown example can be written with less repetition as:
``
== Dog

Cute animal.

\x[cats]{c} are its natural enemies.

== Cats

This is the natural enemy of a \x[dog].

\x[dog]{p} are cute, but they are still the enemy.

One example of a cat is \x[Felix the Cat].

=== Felix the Cat
{c}

Felix is not really a \x[cats][cat], just a carton character.
``

If plural and capitalization don't handle your common desired inflections, you can also just create custom ones with the \x[h-synonym-argument].

Now for a live example for quick and dirty interactive testing.

= Cross reference title inflection example
{parent=cross-reference-title-inflection}

\CirodownExample[[
\x[inflection-example-not-proper]
]]

\CirodownExample[[
\x[inflection-example-not-proper]{c}
]]

\CirodownExample[[
\x[inflection-example-not-proper]{full}
]]

\CirodownExample[[
\x[inflection-example-proper]
]]

\CirodownExample[[
\x[inflection-example-proper]{c}
]]

\CirodownExample[[
\x[inflection-example-not-proper-lower]
]]

\CirodownExample[[
\x[inflection-example-not-proper-lower]{c}
]]

\CirodownExample[[
\x[inflection-example-proper-lower]
]]

\CirodownExample[[
\x[not-readme]
]]

\CirodownExample[[
\x[not-readme]{c}
]]

\CirodownExample[[
\x[inflection-example-not-proper]{p}
]]

\CirodownExample[[
\x[inflection-plural-examples]
]]

\CirodownExample[[
\x[inflection-plural-examples]{p}
]]

\CirodownExample[[
\x[inflection-plural-examples]{p=0}
]]

\CirodownExample[[
\x[inflection-plural-examples]{p=1}
]]

\CirodownExample[[
\x[not-the-readme-header-with-fixed-case]
]]

= Inflection example not-proper
{parent=cross-reference-title-inflection-example}

= Inflection example proper
{c}
{parent=cross-reference-title-inflection-example}

= inflection example not-proper lower
{parent=cross-reference-title-inflection-example}

= inflection example proper lower
{c}
{parent=cross-reference-title-inflection-example}

= Inflection plural examples
{parent=cross-reference-title-inflection-example}

= `\x` within `title` restrictions
{parent=internal-cross-reference}

If you use `\x` within a `title`, which most commonly happens for \x[image][image titles], that can generate complex dependencies, which would either be harder to implement, or lead to infinite recursion.

To prevent such problems, Cirodown emits an error if you use an `\x` without content in the `title` of one of the following elements without an explicit ID:
* \x[header]. For example, the following gives an error:
  ``
  = h1
  {id=myh1}

  == \x[myh1]
  ``

  This could be solved by either adding a content to the reference:
  ``
  = h1
  {id=myh1}

  == \x[myh1][mycontent]
  ``
  or by adding an explicit ID to the header:
  ``
  = h1
  {id=myh1}

  == \x[myh1]
  {id=myh2}
  ``
* non-header (e.g. an \x[image]) that links to the title of another non-header

  For non-headers, things are a bit more relaxed, and we can link to headers, e.g.:
  ``
  = h1

  \Image[myimg.jpg]
  {title=my \x[h1].}
  ``
  This is allowed because Cirodown calculates IDs in two stages: first for all headers, and only later non non-headers.

  What you cannot do is link to another image e.g.:
  ``
  \Image[myimg.jpg]
  {id=myimage1}
  {title=My image 1.}

  \Image[myimg.jpg]
  {title=my \x[h1].}
  ``
  and there the workaround are much the same as for headers: either explicitly set the cross reference content:
  ``
  \Image[myimg.jpg]
  {id=myimage1}
  {title=My image 1.}

  \Image[myimg.jpg]
  {title=my \x[h1][My image 1].}
  ``
  or explicitly set an ID:
  ``
  \Image[myimg.jpg]
  {id=myimage1}
  {title=My image 1.}

  \Image[myimg.jpg]
  {id=myimage2}
  {title=my \x[h1].}
  ``

While it is technically possible implement the above limitations, it would require a bit of extra work which we don't want to put in right now: https://github.com/cirosantilli/cirodown/issues/95[].

Furthermore, the above rules do not exclude infinite rendering loops, but Cirodown detects such loops and gives a nice error message, this has been fixed at: https://github.com/cirosantilli/cirodown/issues/34 

For example this would contain an infinite loop:
``
\Image[myimg.jpg]
{id=myimage1}
{title=\x[myimage2].}

\Image[myimg.jpg]
{id=myimage2}
{title=\x[myimage1].}
``

This infinite recursion is fundamentally not technically solved: the user has to manually break the loop by providing an `x` content explicitly, e.g. in either:
``
\Image[myimg.jpg]
{id=myimage1}
{title=\x[myimage2][my content 2].}

\Image[myimg.jpg]
{id=myimage2}
{title=\x[myimage1].}
``
or:
``
\Image[myimg.jpg]
{id=myimage1}
{title=\x[myimage2].}

\Image[myimg.jpg]
{id=myimage2}
{title=\x[myimage1][my content 1].}
``

= Internal cross file reference
{parent=internal-cross-reference}

Reference to the first header of another file:
\CirodownExample[[
\x[not-readme]
]]

Reference to a non-first header of another file:
\CirodownExample[[
\x[h2-in-not-the-readme]
]]

To make toplevel links cleaner,if target header is the very first element of the other page, then the link does not get a fragment, e.g.: `\x[not-readme]` rendered as:
``
<a href="not-readme"
``
and not:
``
<a href="not-readme#not-readme"
``
while `\x[h2-in-not-the-readme]` is rendered with the fragment:
``
<a href="not-readme#h2-in-not-the-readme"
``

Reference to the first header of another file that is a second inclusion:
\CirodownExample[[
\x[included-by-not-readme]
]]

Reference to another header of another file, with \x[x-full-argument][`full`]:
\CirodownExample[[
\x[h2-in-not-the-readme]{full}.
]]
Note that when `full` is used with references in another file in \x[embed-includes][multi page mode], the number is not rendered as explained at: \x[x-full-argument-in-internal-cross-file-references]{full}.

Reference to an image in another file:
\CirodownExample[[
\x[image-not-readme-xi]{full}.
]]

Reference to an image in another file:
\CirodownExample[[
\x[image-figure-in-not-the-readme-without-explicit-id]{full}.
]]

Remember that the \x[the-toplevel-header][ID of the toplevel header] is automatically derived from its file name, that's why we have to use:
\CirodownExample[[
\x[not-readme]
]]
instead of:
``
\x[not-the-readme]
``

Reference to a subdirectory:
\CirodownExample[[
\x[subdir]

\x[subdir/h2]

\x[subdir/notindex]

\x[subdir/notindex-h2]
]]
Implemented at: https://github.com/cirosantilli/cirodown/issues/116

Reference to an internal header of another file: \x[h2-in-not-the-readme]. By default, That header ID gets prefixed by the ID of the top header.

When using \x[embed-includes] mode, the cross file references end up pointing to an ID inside the current HTML element, e.g.:
``
<a href="#not-readme">
``
rather than:
``
<a href="not-readme.html/#not-readme">
``
This is why IDs must be unique for elements across all pages.

= Internal cross file reference internals
{parent=internal-cross-file-reference}
{title2=`db.sqlite3`}

= ID database
{c}
{synonym}

When running in Node.js, Cirodown dumps the IDs of all processed files to a `out/db.sqlite3` file in \x[the-out-directory], and then reads from that file when IDs are needed.

When converting under a directory that contains \x[cirodown-json], `out/db.sqlite3` is placed inside the same directory as the `cirodown.json` file.

If there is no `cirodown.json` in parent directories, then `out/db.sqlite3` is placed in the current working directory.

These follows the principles described at: \x[the-current-working-directory-does-not-matter-when-there-is-a-cirodown-json].

`db.sqlite3` is not created or used when handling input from stdin.

When running in the browser, the same JavaScript API will send queries to the server instead of a local SQLite database.

To inspect the ID database to debug it, you can use:
``
sqlite3 out/db.sqlite3 .dump
``

It is often useful to dump a single table, e.g. to dump the `ids` table:
``
sqlite3 out/db.sqlite3 '.dump ids'
``
and one particularly important query is to dump a list of all known IDs:
``
sqlite3 out/db.sqlite3 'select id from ids'
``

You can force `cirodown` to not use the ID database with `--no-db`:
``
./cirodown --no-db .
``

= Internal cross reference title link removal
{parent=internal-cross-file-reference}

If the target `title` argument contains a link from either another \x[internal-cross-reference]{p} or a regular \x[link][external hyperlink], Cirodown automatically prevents that link from rendering as a link when no explicit body is given.

This is done because https://stackoverflow.com/questions/9882916/are-you-allowed-to-nest-a-link-inside-of-a-link[nested links are illegal in HTML], and the result would be confusing.

This use case is most common when dealing with media such as \x[image]{p}. For example in:
``
= afds

\x[image-aa-zxcv-lolol-bb]

== qwer

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{title=aa \x[zxcv][zxcv] \a[http://example.com][lolol] bb}

== zxcv
``
the `\x[image-aa-zxcv-lolol-bb]` renders something like:
``
<a href="#image-aa-zxcv-lolol-bb">aa zxcv lolol bb</a>
``
and not:
``
<a href="#image-aa-zxcv-lolol-bb">aa <a href="zxcv">zxcv</a> <a href="http://example.com">lolol</a> bb</a>
``

Live example:
\CirodownExample[[
This is a nice image: \x[image-aa-zxcv-lolol-bb].

\Image[Tank_man_standing_in_front_of_some_tanks.jpg]
{title=aa \x[internal-cross-reference-title-link-removal][zxcv] \a[http://example.com][lolol] bb}
]]

= `\x` arguments
{parent=internal-cross-reference}

= `\x` `c` argument
{parent=x-arguments}

Capitalizes the first letter of the target title.

For more details, see: \x[cross-reference-title-inflection]{full}.

= `\x` `child` argument
{parent=x-arguments}

Setting the `child` \x[boolean-named-argument] on a cross reference to a header as in:
``
\x[my-header]{child}
``
makes that header show up on the list of extra parents of the child.

This allows a section to have multiple parents, e.g. to include it into multiple categories. For example:
``
= Animal

== Mammal

=== Dog

=== Cat

== Cute animal

These animals are cute:
* \x[dog]{child} because they play with you

These animals aren't cute however:
* \x[cat]
``
would render something like:
``
h1 Animal

h2 Mammal

h3 Dog (parent section: Mammal)
(other parent sections: Cute animal)

h3 Cat (parent section: Mammal)

== Cute animal

These animals are cute:
* \x[dog]

These animals aren't cute however:
* \x[cat]
``
so note how "Dog" has a list of extra parents including "Cute animal", but Cat does not, due to the `child`.

This property does not affect how the \x[table-of-contents][`\Toc`] is rendered. We could insert elements sections there multiple times, but it has the downside that browser Ctrl + F searches would hit the same thing multiple times on the table of contents, which might make finding things harder.
``
== My title{id=my-id}

Read this \x[my-id][amazing section].
``

If the second argument, the `content`, is not present, it expand to the header title, e.g.:
``
== My title{id=my-id}

Read this \x[my-id].
``
is the same as:
``
== My title{id=my-id}

Read this \x[my-id][My title].
``

A live demo can be seen at: \x[x-child-argument-demo].

= `\x` `child` argument demo
{parent=x-child-argument}
{scope}

= Animal
{parent=x-child-argument-demo}

= Mammal
{parent=animal}

= Dog
{parent=mammal}

= Cat
{parent=mammal}

= Cute animal
{parent=animal}

Cute animal:
* \x[dog]{child}
* \x[cat]

= `\x` `parent` argument
{parent=x-child-argument}

The `parent` argument is exactly like the \x[x-child-argument], but it reverses the direction of the parent/child relation.

= `\x` `full` argument
{parent=x-arguments}

To also show the section auto-generated number as in "Section X.Y My title" we add the optional `{full}` \x[boolean-named-argument] to the cross reference, for example:
\CirodownExample[[
\x[x-full-argument]{full}.
]]

`{full}` is not needed for cross references to most macros besides \x[header]{p}, which use `full` by default as seen by the `default_x_style_full` macro property in \x[help-macros]. This is for example the case for \x[image]{p}. You can force this to be disabled with `{full=0}`:
\CirodownExample[[
Compare \x[image-my-test-image]{full=0} vs \x[image-my-test-image]{full=1}.
]]

= `\x` `full` argument in internal cross file references
{parent=x-full-argument}

For example in the following \x[internal-cross-file-reference]:
\CirodownExample[[
\x[h2-in-not-the-readme]{full}.
]]
we get just something like:
``
Section "h2 in not the readme"
``
instead of:
``
Section 1.2 "h2 in not the readme"
``
This is because the number "Section 1.2" might already have been used in the current page, leading to confusion.

= `\x` `p` argument
{parent=x-arguments}

Pluralizes or singularizes the last word of the target title.

For more details, see: \x[cross-reference-title-inflection]{full}.

= `\x` `ref` argument
{parent=x-arguments}

The `ref` argument of `\x` marks the link as reference, e.g.:
``
Trump said this and that.\x[donald-trump-access-hollywood-tape]{ref}

= Donald Trump Access Hollywood tape
``
renders something like:
``
Trump said this and that.<a href="donald-trump-access-hollywood-tape">*</a>
``

This could currently be replicated without `ref` by just using:
``
Trump said this and that.\x[donald-trump-access-hollywood-tape][*]
``
but later on we might add more precise reference fields like the page of a book or date fetched as Wikipedia supports.

Implemented at: https://github.com/cirosantilli/cirodown/issues/137

== Cirodown syntax

=== Insane macro shortcuts

Certain commonly used macros have insane macro shortcuts that do not start with backslash (`\`).

Originally, \x[design-goals][Ciro wanted to avoid those], but they just feel too good to avoid.

Every insane syntax does however have an equivalent sane syntax.

The style recommendation is: use the insane version which is shorter, unless you have a specific reason to use the sane version.

= Macros with insane shortcut
{parent=insane-macro-shortcuts}

* \x[paragraph]{child}{full}: `\n\n` (double newline)
* \x[link]{child}{full}: `a http://example.com b` (space followed by `http://`)
* \x[mathematics]{child}{full}: `$`, described at: \x[insane-code-and-math-shortcuts]
* \x[code-block]{child}{full}: \c[[`]], described at: \x[insane-code-and-math-shortcuts]
* \x[list]{child}{full}: `* ` and indentation
* \x[table]{child}{full}: `|| `, `| ` and indentation

==== Insane code and math shortcuts

The insane code and math shortcuts work very analogously and are therefore described together in this section.

The insane inline code syntax:
\CirodownExample[[
a `b c` d
]]
and is equivalent to the sane:
``
a \c[[b c]] d
``

The insane block code:
\CirodownExample[[
a

``
b c
``

d
]]
and is equivalent to the sane:
``
a

\C[[
b c
]]

d
``

==== Insane macro shortcut extra arguments

Insane arguments always work by abbreviating:
* the macro name
* one or more of its positional arguments, which are fixed as either \x[literal-arguments][literal or non-literal] for a given insane construct
This means that you can add further arguments as usual.

For example, an insane code block with an id can be written as:
``
a `b c`{id=ef} g
``
because that is the same as:
\CirodownExample[[
a \c[b c]{id=ef} g
]]
So we see that the `b c` argument is the very first argument of `\c`.

Extra arguments must come after the insane opening, e.g. the following does not work:
``
a {id=ef}`b c` g
``

This restriction things easy to parse for humans and machines alike.

==== Escapes in insane macro shortcuts

Literal backticks and dollar signs can be produced witha backslash escape as in:
\CirodownExample[[
a \` \$ b
]]

It is not possible to escape backticks (\c[[`]]) inside an insane inline code, or dollar signs (`$`) in insane math.

The design reason for that is because multiple backticks produce block code.

The upside is that then you don't have to escape anything else, e.g. backslashes (`\`) are rendered literally.

The only way to do it is to use the sane syntax instead:
\CirodownExample[[[
a \c[[b ` c]] d

a \m[[\sqrt{\$4}]] d
]]]

Within block code and math, you can just add more separators:
\CirodownExample[[
```
code with two backticks
``
nice
```
]]

=== Macro argument syntax

==== Positional vs named arguments
{title2=`[...]` vs `{key=...}`}

Every argument in Cirodown is either positional or named.

For example, in a \x[header] definition with an ID:
``
= My asdf
{id=asdf qwer}
{scope}
``
which is equivalent to the \x[insane-macro-shortcuts][sane] version:
``
\H[1][My asdf]
{id=asdf qwer}
{scope}
``
we have:
* two positional argument: `[1]` and `[My asdf]`. Those are surrounded by square brackets `[]` and have no name
* two named arguments: `{id=asdf qwer}` and `{scope}`.

  The first one has name `id`, followed by the separator `=`, followed by the value `asdf qwer`.

  The separator `=` always is optional. If not given, it is equivalent to an empty value, e.g.:
  ``
  {id=}
  ``
  is the same as:
  ``
  {id}
  ``

You can determine if a macro is positional or named by using \x[help-macros]. Its output contains something like:
``
  "h": {
    "name": "h",
    "positional_args": [
      {
        "name": "level"
      },
      {
        "name": "content"
      }
    ],
    "named_args": {
      "id": {
        "name": "id"
      }
      "scope": {
        "name": "scope"
      }
    },
``
and so we see that `level` and `content` are positional arguments, and `id` and `scope` are named arguments.

Generally, positional arguments are few (otherwise it would be hard to know which is which is which), and are almost always used for a given element so that they save us from typing the name too many times.

The order of positional arguments must of course be fixed, but named arguments can go anywhere. We can even mix positional and named arguments however we want, although this is not advised for clarity.

The following are therefore all equivalent:
``
\H[1][My asdf]{id=asdf qwer}{scope}
\H[1][My asdf]{scope}{id=asdf qwer}
\H{id=asdf qwer}{scope}[1][My asdf]
\H{scope}[1]{id=asdf qwer}[My asdf]
``

Just like named arguments, positional arguments are never mandatory.

===== Positional argument default values

Most positional arguments will default to an empty string if not given.

However, some positional arguments can have special effects if not given.

For example, an anchor with the first positional argument present (the URL), but not the second positional argument (the link text) as in:
\CirodownExample[[
\a[http://example.com]
]]
has the special effect of generating automatic links as in:
``
\a[http://example.com][http://example.com]
``

This can be contrasted with named arguments, for which there is always a default value, notably for \x[boolean-named-argument]{p}.

See also: \x[link]{full}.

====== mandatory positional arguments

Some positional arguments are required, and if not given Cirodown reports an error and does not render the node.

This is for example the `level` of a \x[header].

These arguments marked with the `mandatory: true` \x[help-macros] argument property.

===== Boolean named argument

Name arguments marked in \x[help-macros] as `boolean: true` must either:
* take no value and no `=` sign, in which case the value is implicitly set to `1`
* take value exactly `0` or `1`
* not be given, in which case a custom per-macro default is used. Tha value is the `default` from \x[help-macros], or `0` if such default is not given

For example, \x[x-full-argument][the `full` argument] of \x[internal-cross-reference]{p} is correctly written as:
\CirodownExample[[
\x[boolean-named-argument]{full}
]]
without the `=` sign, or equivalently:
\CirodownExample[[
\x[boolean-named-argument]{full=1}
]]
The `full=0` version is useful in the case of reference targets that unlike \x[header]{p} expand the title on the cross reference by default, e.g. \x[image]{p}:
\CirodownExample[[
\x[boolean-named-argument]{full=1}
]]

The name "boolean argument" is given by analogy to the https://stackoverflow.com/questions/16109358/what-is-the-correct-readonly-attribute-syntax-for-input-text-elements/24588427#24588427["boolean attribute" concept in HTML5].

==== JavaScript interface for arguments
{c}

The JavaScript interface sees arguments as follows:
``
function macro_name(args)
``
where args is a dict such that:
* optional arguments have the key/value pairs explicitly given on the call
* mandatory arguments have a key documented by the API, and the value on the call.

  For example, the link API names its arguments `href` and `text`.

==== Literal arguments
{title2=`[[...]]` and `{{key=...}}`}

Arguments that are opened with more than one square brackets `[` or curly braces `{` are literal arguments.

In literal arguments, Cirodown is not parsed, and the entire argument is considered as text until a corresponding close with the same number of characters.

Therefore, you cannot have nested content, but it makes it extremely convenient to write \x[code-block]{p} or \x[mathematics].

For example, a multiline code block with double open and double close square brackets inside can be enclosed in triple square brackets:
\CirodownExample[[[
A literal argument looks like this in Cirodown:

\C[[
\C[
A multiline

code block.
]
]]

And another paragraph.
]]]

The same works for inline code:
\CirodownExample[[[
The program \c[[puts("]");]] is very complex.
]]]

Within literal blocks, only one thing can be escaped with backslashes are:
* leading open square bracket `[`
* trailing close square bracket `]`

The rule is that:
* if the first character of a literal argument is a sequence of backslashes (`\`), and it is followed by another argument open character (e.g. `[`, remove the first `\` and treat the other characters as regular text
* if the last character of a literal argument is a `\`, ignore it and treat the following closing character (e.g. `]`) as regular text

See the following open input/output pairs:
``
\c[[\ b]]
<code>\ b</code>

\c[[\a b]]
<code>\a b</code>

\c[[\[ b]]
<code>[ b</code>

\c[[\\[ b]]
<code>\[ b</code>

\c[[\\\[ b]]
<code>\\[ b</code>
``
and close examples:
``
\c[[a \]]
<code>a \</code>

\c[[a \]]]
<code>a ]</code>

\c[[a \\]]]
<code>a \]</code>
``

==== Argument leading newline removal

If the very first character of an argument is a newline, then that character is ignored if it would be part of a regular plaintext node.

For example:
``
\C[[
a

b
]]
``
generates something like:
``
<pre><code>a

b
</code></pre>
``
instead of:
``
<pre><code>
a

b
</code></pre>
``
This is extremely convenient to improve the readability of code blocks and similar constructs.

The newline is however considered if it would be part of some \x[insane-macro-shortcuts]{p=0}. For example, we can start an \x[list][insane list] inside a \x[quotation]{p} as in:
\CirodownExample[[
\Q[
* a
* b
]
]]
where the insane list requires a leading newline `\n* ` to work. That newline is not ignored, even though it comes immediately after the `\Q[` opening.

==== Argument newlines between arguments removal

The macro name and the first argument, and two consecutive arguments, can be optionally separated by exactly one newline character, e.g.:
``
\H[2]
{scope}
[Design goals]
``
is equivalent to:
``
\H[2]{scope}[Design goals]
``
and this non-recommended mixed style:
``
\H[2]{scope}
[Design goals]
``
This allows to greatly improve the readability of long argument lists by having them one per line.

There is one exception to this however: inside an \x[header][insane header], any newline is interpreted as the end of the insane header. This is why the following works as expected:
``
== My header 2 `some code`
{id=asdf}
``
and the `id` gets assigned to the header rather than the trailing code element.

==== Escape characters

For \x[literal-arguments][non-literal macro arguments], you have to use a backslash to escape:
* `\`: backslashes start macros
* `\` and `\`: open and close \x[positional-vs-named-arguments][positional macro arguments]
* `\` and `\`: open and close \x[positional-vs-named-arguments][optional macro arguments]
* `$` (dollar sign): \x[insane-macro-shortcuts][insane macro shortcut] for \x[mathematics]
* \c[[`]] (backtick): \x[insane-macro-shortcuts][insane macro shortcut] for \x[code-block]{p}

The escape rules for literal arguments are described at: \x[literal-arguments]{full}.

This is good for short arguments of regular text, but for longer blocks like \x[code-block]{p} or \x[mathematics], you may want to use \x[literal-arguments]

==== `auto_parent` macro property
{id=auto-parent}

Some sequences of macros such as `l` from \x[list]{p} and `tr` from \x[table]{p} automatically generate implicit parents, e.g.:
``
\Ul[
\L[aa]
\L[bb]
]
``
parses exactly like:
``
\L[aa]
\L[bb]
``

The children are always added as arguments of the `content` argument of the implicit parent.

If present, the `auto_parent` macro property determines which auto-parent gets added to those macros.

==== `remove_whitespace_children` macro argument property
{id=remove-whitespace-children}

In HTML, certain elements such as `<ul>` cannot have any `text` nodes in them, and any whitespace is ignored, see https://stackoverflow.com/questions/2161337/can-we-use-any-other-tag-inside-ul-along-with-li/60885802#60885802[].

A similar concept applies to Cirodown, e.g.:
``
\Ul[
\L[aa]
\L[bb]
]
``
does not parse as:
``
\Ul[\L[aa]<NEWLINE>\L[bb]<NEWLINE>]
``
but rather as:
``
\Ul[\L[aa]\L[bb]]
``
because the `content` argument of `ul` is marked with `remove_whitespace_children` and automatically removes any whitespace children (such as a newline) as a result.

This also applies to consecutive sequences of \x[auto-parent] macros, e.g.:
``
\L[aa]
\L[bb]
``
also does not include the newline between the list items.

The definition of whitespace is the same as the ASCII whitespace definition of HTML5: ` \r\n\f\t`.

=== Block vs inline macros

Every Cirodown macro is either block or inline:
* a block macro is one that takes up the entire line when rendered

  All block macros start with a capital letter, e.g. `\H` for \x[header]{p}.
* and an inline macro is one that goes inside of a line.

  Every inline macro starts with a lowercase letter e.g. `\a` for \x[link]{p}.

Some macros have both a block and an inline version, and like any other macro, those are differentiated by capitalization:
* \x[mathematics]
* \x[code-block]{p}
* \x[comment]{p}

=== Known URL protocols

Certain common URL protocols are treated as "known" by Cirodown, and when found they have special effects in some parts of the conversion.

The currently known protocols are:
* `http://`
* `https://`

Effects of known protocols include:
* \x[insane-link-parsing-rules]: mark the start of insane links
* \x[store-images-in-a-separate-media-repository]: mark an image `src` to ignore `provider`

=== JavaScript case conversion
{c}

Some parts of Cirodown use "JavaScript case conversion".

This means that the conversion is done as if by the `toLowerCase`/`toUpperCase` functions.

The most important fact about those functions is that they do convert non-ASCII Unicode capitalization, e.g. between `É` and `é`:
* https://stackoverflow.com/questions/3590833/does-javascript-string-tolowercase-follow-unicode-standards-in-case-conversion
* https://stackoverflow.com/questions/929079/unicode-lowercase-characters

These conversions are also specified in the Unicode standard.

=== Security

= `--unsafe-ace`
{parent=security}

Cirodown is designed to not allow arbitrary code execution by default on any Cirodown command.

This means that it it should be safe to just download any Cirodown repository, and convert it with the Cirodown executable, even if you don't trust its author.

This option enables actions that would allow such code execution, so you should only pass it if you trust the repository author. Enabled functionality includes:
* \x[cirodown-json/prepublish]

Note however that you have to be careful in general, since e.g. a malicious author could create a package with their own malicious version of the `cirodown` executable, that you could unknowingly run with with the standard `npx cirodown` execution.

= unsafe-xss
{title2=`--unsafe-xss`}
{parent=security}

Cirodown HTML output is designed to be XSS safe by default, any non-XSS safe constructs must be enabled with a non-default flag or setting, see: \x[unsafe-xss].

Of course, we are walking on eggs, and this is hard to assert, so the best thing to do later on will be to parse the output e.g. with https://developer.mozilla.org/en-US/docs/Web/API/DOMParser[`DOMParser`] to ensure that it is valid and does not contain any `script` tags, but it is not as simple as that: https://stackoverflow.com/questions/37435077/execute-javascript-for-xss-without-script-tags/61588322#61588322

XSS unsafe constructs lead to errors by default. XSS unsafe constructs can be allowed \x[cirodown-executable][from the command] line with:
``
./cirodown --unsafe-xss
``
or from the \x[cirodown-json] file with an entry of form:
``
"unsafe-xss": true
``

== Tooling

Unlike all languages which rely on ad-hoc tooling, we will support every single tool that is required and feasible to be in this repository in this repository, in a centralized manner.

=== `cirodown` executable

Convert a `.ciro` file to HTML and output the HTML to a file with the same basename without extension, e.g.:
``
cirodown hello.ciro
firefox hello.html
``

Files named `README.ciro` are automatically converted to `index.html` so that they will show on both GitHub READMEs and at the website's base address:
``
cirodown README.ciro
firefox hello.html
``

Convert all `.ciro` files in a directory to HTML files next to each corresponding `.ciro` file, e.g. `somefile.ciro` to `somefile.html`:
``
cirodown .
``
The HTML output files are placed right next to each corresponding `.ciro`.

The output file can be selected explicitly with: \x[outfile].

Output to stdout instead of saving it to a file:
``
cirodown --stdout README.ciro
``

In order to resolve \x[internal-cross-file-reference]{p}, this actually does two passes:
* first an ID extraction pass, which parses all inputs and dumps their IDs to the ID database
* then a second render pass, which uses the IDs in the ID database

Convert a `.ciro` file from stdin to HTML and output the contents of `<body>` to stdout:
``
printf 'ab\ncd\n' | cirodown --body-only
``

= Index files
{parent=cirodown-executable}

The following basenames are considered "index files":
* `README.ciro`
* `index.ciro`

Those basenames have the following magic properties:
* the default output file name for an index file in HTML output is always `index.html`, including that of `README.ciro`. This way it will appear on both the root of the HTML output and on the GitHub home page once GitHub adds Cirodown support.
* the default \x[the-toplevel-header][toplevel header] ID of an index files is derived from the parent directory basename rather than from the source file basename

= Project toplevel directory
{parent=the-toplevel-index-file}

This directory is determined by first checking the presence of a \x[cirodown-json] file.

If a \x[cirodown-json] is found, then the project toplevel directory is the directory that contains that file.
* otherwise, if the input path is a descendant of the current working directory, then the current working directory is used, see also: \x[the-current-working-directory-does-not-matter-when-there-is-a-cirodown-json]
* otherwise, if the input path is a directory, it is used
* otherwise, the directory containing the input file is used

For example, consider the file following file structure relative to the current working directory:
``
path/to/notindex.ciro
``

In this case:
* if there is no `cirodown.json` file:
  * if we run `cirodown .`: the toplevel directory is the current directory `.`, and so `notindex.ciro` has ID `path/to/notindex`
  * if we run `cirodown path`: same
  * if we run `cirodown path/to`: same
  * if we run `cirodown path/to/notindex.ciro`: same
* if there is a `path/cirodown.json` file:
  * if we run `cirodown .`: the toplevel directory is the current directory `.` because the `cirodown.json` is below the entry point and is not seen, and so `notindex.ciro` has ID `path/to/notindex`
  * if we run `cirodown path`: the toplevel directory is the directory with the `cirodown.json`, `path`, and so `notindex.ciro` has ID `to/notindex`
  * if we run `cirodown path/to`: same
  * if we run `cirodown path/to/notindex.ciro`: same

= The toplevel index file
{parent=index-files}

This is the \x[index-file] present in the \x[project-toplevel-directory].

Being the toplevel index file has the following implications compared to other index-files:
* its ID is derived from the header itself, not the directory, see also: \x[the-id-of-the-first-header-is-derived-from-the-filename]

= The current working directory does not matter when there is a `cirodown.json`
{parent=the-toplevel-index-file}

When the file or directory being converted has an ancestor directory with a `cirodown.json` file, then your current working directory does not have any effect on Cirodown output. For example if we have:
``
/project/cirodown.json
/project/README.ciro
/project/subdir/README.ciro
``
then all of the following conversions produce the same output:
* directory conversion:
  * `cd /project && cirodown .`
  * `cd / && cirodown project`
  * `cd project/subdir && cirodown ..`
* file conversion:
  * `cd /project && cirodown README.ciro`
  * `cd / && cirodown project/README.ciro`
  * `cd project/subdir && cirodown ../README.ciro`

When there isn't a `cirodown.json`, everything happens as though there were an empty `cirodown.json` file in the current working directory. So for example:
* outputs that would be placed relative to inputs are still placed in that place, e.g. `README.ciro -> index.html` always stay together
* outputs that would be placed next to the `cirodown.json` are put in the current working directory, e.g. \x[the-out-directory]

Internally, the general philosophy is that the JavaScript API in \a[index.js] works exclusively with paths relative to the \x[project-toplevel-directory]. It is then up to callers such as \a[cirodown] to ensure that filesystem specifics handle the relative paths correctly.

= `cirodown` executable options
{parent=cirodown-executable}

= `--china`
{parent=cirodown-executable-options}

This is the most important option of the software.

It produces a copy of the HTML of https://cirosantilli.com/china-dictatorship to stdout.

The data is stored inside an NPM package, making it hard to censor that information, see also: https://cirosantilli.com/china-dictatorship#mirrors

Usage:
``
cirodown --china > china.html
firefox china.html
``

= `--dry-run`
{parent=cirodown-executable-options}

The `--dry-run` option is a good way to debug \x[publish][`--publish` option], as it builds the publish output files without doing any git commands that would be annoying to revert. So after doing:
``
./cirodown --dry-run --publish .
``
you can just go and inspect the generated HTML to see what would get pushed at:
``
cd out/publish/out/publish/
``
see also: \x[the-out-directory].

Inspiration: https://github.com/cirosantilli/linux-kernel-module-cheat/tree/6d0a900f4c3c15e65d850f9d29d63315a6f976bf#dry-run-to-get-commands-for-your-project

= `--dry-run-push`
{parent=dry-run}

Similar to \x[dry-run], but it runs all git commands except for `git push`, which gives a clearer idea of what `--publish` would actually do including the git operations, but without publishing anything:
``
./cirodown --dry-run --publish .
``

= `--embed-includes`
{parent=cirodown-executable-options}

Makes \x[include]{p} render the included content in the same output file as the include is located, instead of the default behaviour of creating links.

In addition to this:
* \x[internal-cross-file-reference]{p} are disabled, and the cross file ID database does not get updated.

  It should be possible to work around this, but we are starting with the simplest implementation that forbids it.

  The problem those cause is that the IDs of included headers show as duplicate IDs of those in the ID database.

  This should be OK to start with because the more common use case with `--html-sinle-page` is that of including all headers in a single document.

Otherwise, `include` only adds the headers of the other file to the table of contents of the current one, but not the body of the other file. The ToC entries then point to the headers of the included external files.

You may want to use this option together with \x[embed-resources] to produce fully self-contained individual HTML files for your project.

= `--embed-resources`
{parent=cirodown-executable-options}

Embed as many external resources such as images and CSS as possible into the HTML output files, rather than linking to external resources.

The use case for this option is to produce a single HTML file for an entire build that is fully self contained, and can therefore be given to consumers and viewed offline, much like a PDF.

Examples of embeddings done:
* CSS and JavaScript are copy pasted in place into the HTML.

  The default built-in CSS and JavaScript files used by Cirodown (e.g. the KaTeX CSS \x[mathematics][used for mathematics]) are currently all automatically downloaded as NPM package dependencies to cirodown

  Without `--embed-resources`, those CSS and JavaScript use their main cloud CDN URLs, and therefore require Internet connection to view the generated documents.

  The embedded version of the document can be viewed offline however.

  There is however a known bug: KaTeX fonts are not currently embedded, so math won't work properly. The situation is similar as for images, but a bit harder because we also need to fetch the blobs from the CSS, which is likely doable from Webpack:
  * https://github.com/cirosantilli/cirodown/issues/157
  * https://stackoverflow.com/questions/41657087/webpack-inline-font-with-url-loader
  * https://stackoverflow.com/questions/35369419/how-to-use-images-in-css-with-webpack

Examples of embedding that could be implemented in the future:
* \x[image]{p} are downloaded if needed and embedded as `data:` URLs.

  Doing this however has a downside: it would slow the page loading down. The root problem is that HTML was not designed to contain assets, and notably it doesn't have byte position indices that can tell it to skip blobs while parsing, and how to refer to them later on when they show up on the screen. This is kind of why EPUB exists: https://github.com/cirosantilli/cirodown/issues/158

  Images that are managed by the project itself and already locally present, such as those inside the project itself or due to \x[cirodown-json/media-providers] usually don't require download.

  For images linked directly from the web, we maintain a local download cache, and skip downloads if the image is already in the cache.

  To re-download due to image updates, use either:
  * `--asset-cache-update`: download all images such that the local disk timestamp is older than the HTTP modification date with https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since[`If-Modified-Since`]
  * `--asset-cache-update-force`: forcefully redownload all assets

Keep in mind that certain things can never be embedded, e.g.:
* YouTube videos, since YouTube does not offer any download API

= `--generate`
{parent=cirodown-executable-options}

Generate one of the template repositories locally:
* `cirodown --generate default`: a good starter template that illustrates many key Cirodown features
  * https://github.com/cirosantilli/cirodown-template
  * https://cirosantilli.com/cirodown-template
* `cirodown --generate min`: a minimal template that is still sane
  * https://github.com/cirosantilli/cirodown-template-min
  * https://cirosantilli.com/cirodown-template-min
* `cirodown --generate subdir`: a template in which Cirodown source is located a subdirectory `docs/`:
  * https://github.com/cirosantilli/cirodown-template-subdir
  * https://cirosantilli.com/cirodown-template-subdir
  This template illustrates that everything works exactly as if Cirodown source were in the git repository toplevel.

  This is a convenient setup for programming projects that want to use Cirodown for their documentation without polluting their toplevel.

End users almost never want this, because it means that to have a sane setup you need to:
* install Cirodown globally with `npm install -g cirodown`
* generate the template
* then install Cirodown locally again with `npm install`
so maybe we should just get rid of that option and just ensure that we can provide an up-to-date working template for the latest relase.

For now we are keeping this as it is useful to automate the updating of templates during the \x[release-procedure].

= `--help-macros`
{parent=cirodown-executable-options}

You can get an overview of all macros in JSON format with:
``
cirodown --help-macros
``

= `--log`
{parent=cirodown-executable-options}

Give multiple times to enable a list of certain types of logs to stderr help debugging, e.g.:
``
./cirodown --log ast tokens -- README.ciro
``
Note that this follows https://github.com/tj/commander.js/tree/e0e723810357e915210af38ccf5098ffe1fb8e65#variadic-option[commander.js' insane variadic arguments], and thus the `--` is required above.

Values not documented in other sections:
* `ast`: the final parsed AST
* `ast-inside`: print the AST from inside the `cirodown.convert` call before it returns.

  This is useful to debug the program if `cirodown.convert` blows up on the next stages before returning.
* `parse`: parsing steps
* `tokenize`: tokenization steps
* `tokens`: final parsed token stream
* `tokens-inside`: like `ast-inside` but for tokens.

  Also adds token index to the output, which makes debugging the parser way easier.

= `--log headers`
{parent=log}

This nifty little option outputs to stderr what the header graph looks like!

It is a bit like a \x[table-of-contents] in your terminal, for when you need to have a look at the outline of the document to decide where to place a new header, but are not in the mood to open a browser or use the \x[browser-editor-with-preview].

Sample output excerpt for this document:
``
= h1  cirodown
== h2 1 quick-start
== h2 2 design-goals
=== h3 2.1 saner
=== h3 2.2 more-powerful
== h2 3 paragraphs
== h2 4 links
``

This option can also serve as a debug tool for header tree related features (confession: that was its original motivation!).

TODO

= `--no-html-x-extension`
{parent=cirodown-executable-options}

If not given, \x[internal-cross-reference]{p} render with the `.html` extension as in:
``
<a href=not-readme.html#h2-in-not-the-readme>
``

This way, those links will work when rendering locally to `.html` files which is the default behaviour of:
``
cirodown .
``

If given however, the links render without the `.html` as in:
``
<a href=not-readme#h2-in-not-the-readme>
``
which is what is needed for servers such as GitHub Pages, which automatically remove the `.html` extension from paths.

This option is automatically implied when publishing to targets that remove the `.html` extension such as GitHub pages.

= `--outdir <outdir>`
{id=outdir}
{parent=cirodown-executable-options}

Set a custom output directory for the conversion

If not given, the \x[project-toplevel-directory] is used.

Suppose we have an input file `./test.ciro`. Then:
``
cirodown --outdir my_outdir test.ciro
``
places its output at:
``
my_outdir/test.html
``

The same would happen if we instead did a full directory conversion as in:
``
cirodown --outdir my_outdir .
``
The output would also be placed in `my_outdir/test.html`.

= `--outfile <outfie>`
{id=outfile}
{parent=cirodown-executable-options}

Save the output to a given file instead of outputting to stdout:
``
./cirodown --outfile not-readme.html not-readme.ciro
``

The generated output is slightly different than that of:
``
./cirodown not-readme.ciro > not-readme.html
``
because with `--outfile` we know where the output is going, and so we can generate relative includes to default CSS/JavaScript files.

= `-O --output-format <outformat>`
{id=output-format}
{parent=cirodown-executable-options}

Default: `html`.

= `id` output format
{parent=output-format}

This output format is mostly a joke.

It is an intermediate step in \x[automatic-id-from-title], that unlike HTML output does not have any tags.

But we decided to expose it for fun, and to start generalizing Cirodown to multiple outputs, as this is a simple format.

The conversion is very simplistic, it basically just pastes the `content` of most arguments.

Stuff that is primarily non-textual like \x[image]{p} is just completely removed. We could put effort in outputting their title correctly, but meh, not worth the effort.

= Unimplemented output formats
{parent=id-output-format}

= `cirodown` output format
{parent=unimplemented-output-formats}

TODO: https://github.com/cirosantilli/cirodown/issues/83

= `latex` output format
{parent=unimplemented-output-formats}

TODO: https://github.com/cirosantilli/cirodown/issues/38

One day, one day. Maybe.

= `-p, --publish`
{id=publish}
{parent=cirodown-executable-options}

Cirodown tooling is so amazing that we also take care of the HTML publishing for you!

Once publish target is properly setup, all you have to do is run:
``
git add README.ciro
git commit -m 'more content!'
cirodown --publish
``
and your changes will be published to the  default target specified in \x[cirodown-json].

If not specified, the default target is \x[publish-to-github-pages].

Only changes committed to Git are pushed.

Files that `cirodown` knows how to process get processed and only their outputs are added to the published repo, those file types are:
* `.ciro` files are converted to `.html`
* `.scss` files are converted to `.css`
Every other Git-tracked file is pushed as is.

When `--publish` is given, stdin input is not accepted, and so the current directory is built by default, i.e. the following two are equivalent:
``
./cirodown --publish
./cirodown --publish .
``

Publishing only happens if the build has no errors.

= Publish to GitHub Pages
{parent=publish}

https://pages.github.com/[GitHub pages] is the default Cirodown publish target.

Since that procedure is so important, it is documented directly at: \x[play-with-the-template].

= Publish to GitHub pages root page
{parent=publish-to-github-pages}

If you want to publish your root user page, which appears at `/` (e.g. https://github.com/cirosantilli/cirosantilli.github.io for the user `cirosantilli`), GitHub annoyingly forces you to use the `master` branch for the HTML output:
* https://github.com/isaacs/github/issues/212
* https://stackoverflow.com/questions/31439951/how-can-i-use-a-branch-other-than-master-for-user-github-pages

This means that you must place your `.ciro` input files in a branch other than `master` to clear up `master` for the generated HTML.

`cirodown` automatically detects if your repository is a root repository or not by parsing `git remote` output, but you must setup the branches correctly yourself.

So on a new repository, you must https://stackoverflow.com/questions/42871542/how-to-create-a-git-repository-with-the-default-branch-name-other-than-master[first checkout to a different branch] as in:
``
git init
git checkout -b dev
``
or to move an existing repository to a non-master branch:
``
git checkout -b dev
git push origin dev:dev
git branch -D master
git push --delete origin master
``

You then will also want to set your default repository branch to `dev` in the settings for that repository: https://help.github.com/en/github/administering-a-repository/setting-the-default-branch

= `-P, --publish-commit <commit-message>`
{id=publish-commit}
{parent=cirodown-executable-options}

Like \x[publish], but also automatically:
* `git add -u` to automatically add change to any files that have been previously git tracked
* `git commit -m <commit-message>` to create a new commit with those changes

This allows you to publish your changes live in a single command such as:
``
cirodown --publish-commit 'my amazing change' .
``

With great power comes great responsibility of course, but who cares!

= `--split-headers`
{parent=cirodown-executable-options}

Split each header into its own separate HTML output file.

This option allows you to keep all headers in a single file, which is much more convenient than working with a billion separate source files, and let them grow naturally as new information is added, but still be able to get a small output page on the rendered website that contains just the content of the given header. Such split pages load faster on the browser, and might get better Google PageRank.

For example given an input file called `hello.ciro` and containing:
``
= h1

h1 content.

A link to another section: \x[h1-1].

== h1 1

h1-1 content.

== h1 1 1

h1-1-1 content.

== h1 1 2

h1-1-2 content.
``
a conversion command:
``
cirodown --split-headers hello.ciro
``
would produce the following output files:
* `hello.html`: contains the entire rendered document as usual.

  Remember that this is called `hello.html` instead of `h1.html` because \x[the-toplevel-header][the toplevel header ID is automatically derived from its filename].

  Each header contains a on-hover link to the single-file split version of the header.
* `hello-split.html`: contains only the contents directly under `= h1`, but not under any of the subheaders, e.g.:
  * `h1 content.` appears in this rendered output
  * `h1-1-1` does not appear in this rendered output
  The `-split` suffix can be customized with the \x[h-splitsuffix-argument] option.
  The `-split` suffix is appended in order to differentiate the output path from `hello.html`
* `h1-1.html`, `h1-1-1.html`, `h1-1-2.html`: contain only the contents direcly under their headers, analogously to `hello-split.html`, but now we don't need to worry about the input filename and collisiont, and just directly use the ID of each header

`--split-headers` is implied by \x[publish]: the published website will automatically get the split pages. There is no way to turn it off currently. A pull request would be accepted, especially if it offers a \x[cirodown-json] way to do it. Maybe it would be nice to have a more generalized way of setting any CLI option equivalent from the `cirodown.json`, and an option `cli` vs `cli-publish` so that `cli-publish` is publish only. Just lazy for now/not enough pressing use case met.

= Internal cross reference targets in split headers
{parent=split-headers}

By defeault, all internal cross references point to the non-split version of headers, including those found in split headers.

The rationale for this is that it gives readers the most context around the header by simply scrolling.

For example, considering the example document at \x[split-headers], \x[internal-cross-reference]{p} such as `\x[h1-1]` would point:
* from the non-split `hello.html` to the section in the current non-split file `#h1-1`
* from split `hello-split.html` to the same section in non-split file with `hello.html#h1-1`
The same applies to \x[internal-cross-file-reference]{p} when there are multiple input files.

In order to make the split version be the default for some headers, you can use the \x[h-splitdefault-argument].

= `--watch`
{parent=cirodown-executable-options}

Don't quit `cirodown` immediately.

Instead, watch the selected file or directory for changes, and rebuild individual files when changes are detected.

Watch every `.ciro` file in an entire directory:
``
cirodown --watch .
``
When a directory is given as the input path, this automatically first does an ID extraction pass on all files to support \x[internal-cross-file-reference]{p}.

Now you can just edit any Cirodown file such has `README.ciro`, save the file in your editor, and refresh the webpage and your change should be visible, no need to run a `cirodown` command explicitly every time.

Exit by entering Ctrl + C on the terminal.

Watch a single file:
``
cirodown --watch README.ciro
``
When a single file is watched, the reference database is not automatically updated. If it is not already up-to-date, you should first update it with:
``
cirodown .
``
otherwise you will just get a bunch of undefined ID errors every time the input file is saved.

TODO: integrate Live Preview: https://asciidoctor.org/docs/editing-asciidoc-with-live-preview/ to also dispense the browser refresh.

= `--template`
{parent=cirodown-executable-options}

Select a custom https://github.com/harttle/liquidjs[Liquid template] file for the output.

The recommended file name for this file is:
``
main.liquid.html
``
which is already ignored by default from the published output.

This repository has a sample `main.liquid.html` at: \a[main.liquid.html].

If not given, the default template at one point was:
``
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>{{ title }}</title>
<style>{{ style }}</style>
</head>
<body class="cirodown">
{{ body }}
</body>
</html>
``
This will get out of sync sooner or later with the code, but this should still serve as a good base example for this documentation.

Defined variables:
* `body`: the rendered body
* `git_sha`: SHA of the latest git commit of the source code if in a git repository
* `html_ext`: `.html` for local renders, empty for server renders.

  So e.g. to link to an ID `myid` you can use:

  ``
  <a href="{{ root_relpath }}myid{{ html_ext }}">
  ``

  This will ideally be replaced with a more generic link to arbitrary ID mechnism at some point: https://github.com/cirosantilli/cirodown/issues/135
* `root_page`: relative path to the toplevel page, e.g. either `index.html`, `../index.html` locally or `./`, `../` on server oriented rendereing
* `root_replath`: relative path from the rendered output to the toplevel directory.

  This allows for toplevel resources like CSS to be found seamlessly form inside subdirectories, specially when rendering locally.

  For example, for the toplevel \x[css] `main.css` which is generated from \a[main.scss], we can use:
  ``
  <link rel="stylesheet" type="text/css" href="{{ root_relpath }}main.css">
  ``

  Then, when a file is locally, for example under a subdirectory `mysubdir/myfile.html`, Cirodown will set:
  ``
  root_relpath=../
  ``
  giving the desired:
  ``
  <link rel="stylesheet" type="text/css" href="../main.css">
  ``

  And if the output path were instead just `myohterfile.html`, `root_replath` expands to an empty string, giving again the correct:
  ``
  <link rel="stylesheet" type="text/css" href="main.css">
  ``

  This will ideally be replaced with a more generic link to arbitrary ID mechnism at some point: https://github.com/cirosantilli/cirodown/issues/135
* `style`: default Cirodown stylesheets
* `title`

We pick Liquid because it is server-side safe: if we ever some day offer a compilation service, Liquid is designed to prevent arbitrary code execution and infinite loops in templates.

= `cirodown.json`
{parent=cirodown-executable}
{scope}

Cirodown configuration file that affects the behaviour of cirodown for all files in the directory.

`cirodown.json` not used for input from stdin, since we are mostly doing quick tests in that case.

While `cirodown.json` is optional, it is used to determine the toplevel directory of a Cirodown project, which has some effects such as those mentioned at \x[the-toplevel-index-file].

Therefore, it is recommended that you always have a `cirodown.json` in your project's toplevel directory, even if it is going to be an empty JSON containing just:
``
{}
``

For example, if you convert a file in a subdirectory such as:
``
cirodown subdir/notindex.ciro
``
then `cirodown` walks up the filesystem tree looking for `cirodown.json`, e.g.:
* is there a `./subdir/cirodown.json`?
* otherwise, is there a `./cirodown.json`?
* otherwise, is there a `../cirodown.json`?
* otherwise, is there a `../../cirodown.json`?
and so on.

If we reach the root path `/` and no `cirodown.json` is found, then we understand that there is no `cirodown.json` file present.

= `cirodown.json` schema
{parent=cirodown-json}

= `ignore`
{parent=cirodown-json-schema}

List of paths relative to the \x[project-toplevel-directory] that \x[cirodown-executable] will ignore.

Useful if your project has a large directory that does not contain Cirodown sources, and you don't want Cirodown to mess with it.

Only ignores recursive conversions, e.g. given:
``
  "ignore": [
    "web"
  ]
``
doing:
``
cirodown .
``
skips that directory, but
``
cirodown web/myfile.ciro
``
converts it because it was explicitly requested.

TODO: also ignore during \x[watch].

= `media-providers`
{parent=cirodown-json-schema}

The `media-providers` entry of `cirodown.json` specifies properties of how media such as \x[image]{p} and \x[video]{p} are retrieved and rendered.

The general format of `media-providers` looks like:
``
"media-providers": {
  "github": {
    "default-for": ["image"], // "all" to default for both image, video and anything else
    "path": "data/media/",    // data is gitignored, but should not be nuked like out/
    "remote": "cirosantilli/cirodown-media",
  },
  "local": {
    "default-for": ["video"],
    "path": "media/",
  },
  "youtube": {}
}
``

Properties that are valid for every provider:
* `default-for`: use this provider as the default for the given types of listed macros.

  The first character of the macros are case insensitive and must be given as lower case. Therefore e.g.:
  * `image` applies to both `image` and `Image`
  * giving `Image` is an error because that starts with an upper case character
* `title-from-src` (`bool`): extract the `title` argument from the `src` by default for media such as \x[image]{p} and \x[video]{p} as if the `titleFromSrc` macro argument had been given, see also: \x[image-id]

Direct children of media-providers and subproperties that are valid only for them specifically:
* `local`: tracked in the current Git repository as mentioned at \x[store-images-inside-the-repository-itself]{full}
  * `path`: location of the cloned local repository relative to the root the main repository
* `github`: tracked in a separate Git repository as mentioned at \x[store-images-in-a-separate-media-repository]{full}
  * `path`: same as for `local`
  * `remote`: `<github-username>/<repo-name>`
* `youtube`: YouTube \x[video]{p}

See also: https://github.com/cirosantilli/cirodown/issues/40

= `prepublish`
{parent=cirodown-json-schema}

Path of a script that gets executed before running \x[publish][`cirodown --publish`].

The script arguments are:
* the publish output directory.

  That directory is guaranteed to exist when `prepublish` is called.

  For `git`-based publish targets, all files are almost ready in there, just waiting for a `git add .` that follows `prepublish`.

  This means that you can use this script to place or remove files from the final publish output.

If the `prepublish` script returns with a non-zero exit value, the publish is aborted.

= `redirects`
{parent=cirodown-json-schema}

You are generally better using the newer \x[h-synonym-argument] feature instead of `redirects`, as that concentrates more header specific data in the .ciro files it belongs.

Create HTML redirects from \x[the-toplevel-header][toplevel headers] to arbitrary IDs, for example:
``
"redirects": {
  "a-toplevel-directory": "not-readme",
  "quick-start-redirect-test": "quick-start"
},
``
The HTML files are generated whenever a directory compilation is required, e.g. as in `cirodown .`.

The sources must be toplevel headers for now, because it is harder to implement redirections from `#someid` as that would require JavaScript: https://github.com/cirosantilli/cirodown/issues/48[].

This feature can be seen live on this document by visiting our tests:
* \a[not-readme-redirect-test]{check=0}: redirects to \x[not-readme]
* \a[quick-start-redirect-test]{check=0}: redirects to \x[quick-start]

To quickly test bugs in redirect generation, you may use the `--generate-redirects` flag as:
``
cirodown --generate-redirects .
``
which generates the redirects while skipping everything else. A previous:
``
cirodown .
``
is required to generate the ID database.

= Conversion to/from other formats
{parent=tooling}

The only thing we have for now is the quick and dirty \a[adoc-to-ciro].

The better approach would be to implement a converter in Haskell from anything to Cirodown.

And from Cirodown to anything, create new output formats inside Cirodown to those other formats.

= Dynamic website
{parent=tooling}

An implementation of: https://cirosantilli.com/write-free-books-to-get-famous-website

The source of the dynamic website is located under \a[web/].

It was originally forked from the following starter boilerplate: https://github.com/cirosantilli/node-express-sequelize-realworld-example-app

= Local development server
{parent=dynamic-website}

``
cd web/
npm install
npm run dev
``

We also offer shortcuts on toplevel:
``
npm install
npm run dev
``

You might also want to nuke the current database and create a demo database:
``
./bin/generate-demo-data.js
``

The browser automatically pops the development front-end server at http://localhost:4101[] which makes requests to the backend server that runs at http://localhost:3000[].

= Local optimized frontend
{parent=dynamic-website}

``
cd web
npm install
npm run build-dev
npm start
``

The website can now be seen at: http://localhost:3000

This is the type of setup that will run in production, with a single server. Running it locally might help debug some front-end deployment issues. But otherwise you will just normally use the \x[local-run-as-identical-to-deployment-as-possible] setup instead for development.

`build-dev` is needed instead of `build` because it uses `NODE_ENV_OVERRIDE` which is needed because Next.js forces `NODE_ENV=production` and wontfixed changing it: https://github.com/vercel/next.js/issues/4022#issuecomment-374010365[], and that would lead to the PostgreSQL database being used, instead of the SQLite one we want.

Building like this notably runs full typescript type checking, which is a good way to find bugs early.

`build` runs `npm run build-assets` on toplevel which repacks cirodown itself and is a bit slow. To speed things up during the development loop, you can also use:
``
npm run build-dev-nodeps
``
instead, which builds only the stuf under `web/`.

= Local run as identical to deployment as possible
{parent=dynamic-website}

Here we use PostgreSQL instead of SQLite with the prebuilt static frontend.

For when you really need to debug some deployment stuff locally

Setup:

``
createdb node_express_sequelize_realworld
psql -c "CREATE ROLE node_express_sequelize_realworld_user with login password 'a'"
psql -c 'GRANT ALL PRIVILEGES ON DATABASE node_express_sequelize_realworld TO node_express_sequelize_realworld_user'
echo "SECRET=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 256)" >> .env
npm run build
``

Run:

``
env $(cat .env | xargs) \
NODE_ENV=production \
DATABASE_URL='postgres://node_express_sequelize_realworld_user:a@localhost:5432/node_express_sequelize_realworld' \
npm start
``

then visit the running website at: http://localhost:3000/

= Heroku deployment
{c}
{parent=dynamic-website}

Got it running perfectly at as of April 2021 https://cirodown.herokuapp.com/ with the following steps.

Initial setup:
``
sudo snap install --classic heroku
heroku login
heroku git:remote -a cirodown
# Automatically sets DATABASE_URL.
heroku addons:create heroku-postgresql:hobby-dev
heroku config:set SECRET="$(tr -dc A-Za-z0-9 </dev/urandom | head -c 256)"
``

Every deployment:
``
npm run deploy
``

Nuke the database and generate a demo database:
``
# heroku run web/bin/generate-demo-data.js --force-production
``

= Dependency organization
{parent=heroku-deployment}

On the toplevel we have:
* `.`: Cirodown package
* `web`: \x[dynamic-website] package that depends on the local Cirodown package through relative path `..`

Currently, Heroku deployment does the following:
* install both `dependencies` and `devDependencies`
* `npm run build`
* remove `devDependencies` from the final output to save space and speed some things up

  The `devDependencies` should therefore just contain things which are needed for the build, typically asset compressors like Webpack.

This setup creates some conflict between what we want for Cirodown command line users, and Heroku deployment.

Notably, Cirodown command line users will want SQLite, and Heroku never, and SQLite installation is quite slow.

Since we were unable to find any way to make things more flexible on the `package.json` with some kind of optional depenency, for now we are just hacking out any dependencies that we don't want Heroku to install at all from \a[package.json] and \a[web/package.json] with `sed` rom \a[heroku-prebuild].

Further discussion at: https://github.com/cirosantilli/cirodown/issues/156

= Dynamic website tech stack
{parent=dynamic-website}

* Frontend
  * Next.js
  * React
* Frontend backend communication
  * JSON API
  * Next.js makes its prerender server-side queries directly to the database without going through the API
* Backend
  * Express.js
  * Sequelize
  * SQLite for local development, PostgreSQL for deployment

= Editor support
{parent=tooling}

= Vim
{parent=editor-support}

You can install the support with https://github.com/VundleVim/Vundle.vim[Vundle] with:
``
set nocompatible
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/vundle'
let g:snipMate = {}
let g:snipMate.snippet_version = 1
Plugin 'MarcWeber/vim-addon-mw-utils'
Plugin 'tomtom/tlib_vim'
Plugin 'garbas/vim-snipmate'
Plugin 'cirosantilli/cirodown', {'rtp': 'vim'}
``
or by directly dropping the files named below under your `~/.vim/`, e.g. `vim/syntax/cirodown.vim`

The following support is provided:
* \a[vim/syntax/cirodown.vim]: syntax highlighting.

  As for other programming languages, this cannot be perfect without actually parsing, which would be slow for larger files.

  But even the imperfect approximation already covers a lot of the most cases.

  Notably it turns off spelling from parts of the document like URLs and code which would otherwise contain many false positive spelling errors.
* \a[vim/snippets/cirodown.snippets]: snippets for https://github.com/honza/vim-snippets[], which you also have to install first for them to work.

  For example, with those snippets installed, you can easily create links to headers. Suppose you have:
  ``
  = My long header
  ``
  To create an internal cross reference to it you can:
  * copy `My long header` to the clipboard, see copy to clipboard shortcuts at: https://stackoverflow.com/questions/3961859/how-to-copy-to-clipboard-in-vim/67890119#67890119
  * type `\x` and then hit tab
  and it will automatically expand to:
  ``
  \x[my-long-header]
  ``
  This provides a reasonable alternative for ID calculation, until a ctags-like setup gets implemented (never/\x[browser-editor-with-preview]-only? ;-))

  Similarly for \x[h-parent-argument] you can do:
  ``
  {p
  ``
  would expand to:
  ``
  {parent=my-long-header}
  ``

  Syntax highlighting can likely never be perfect without a full parser (which is slow), but even the imperfect approximate setup (as provided for most other languages) is already a huge usability improvement.

  We will attempt to err on the side of "misses some stuff but does not destroy the entire page below" whenever possible.

= Browser editor with preview
{parent=editor-support}

There are two versions of this editor:
* \a[editor.html] is a toy/demo with no backing database.

  That editor can be viewed directly locally with:
  ``
  git clone https://github.com/cirosantilli/cirodown
  cd cirodown
  npm install
  npm run build-assets
  chrome editor.html
  ``

  It also appears at https://cirosantilli.com/cirodown/editor[] hosted simply under GitHub pages.
* a similar looking editor will also appear on the \x[dynamic-website], but this time linked to the database.

  That more advanced editor will actually save results back to the database, and show allow preview of features such as linking to headers of other pages.

Issues for the editor are being tracked under: https://github.com/cirosantilli/cirodown/labels/editor

We must achieve an editor setup with synchronized live side-by-side preview.

Likely, we will first do a non WYSIWYG editor with side by side preview with scroll sync.

Then, if the project picks up steam, we can start considering a full WYSIWYG.

It would be amazing to have a WebKit interface that works both on browser for the and locally.

Possibilities we could reuse:
* Editor.js

  Returns JSON AST!

  * website: https://editorjs.io/
  * source: https://github.com/codex-team/editor.js
  * WYSIWYG: yes
  * preview scroll sync: yes
* StackEdit
  * markup implementation: PageDown
  * website: https://stackedit.io
  * source: https://github.com/benweet/stackedit
  * demo: https://stackedit.io/app
  * WYSIWYG: no
  * preview scroll sync: yes
* Editor.md
  * website: https://github.com/pandao/editor.md
  * source: https://github.com/pandao/editor.md
  * demo: https://pandao.github.io/editor.md
  * WYSIWYG: no
  * preview scroll sync: yes but buggy when tested 2019-12-12 on live website
* https://github.com/markdown-it/markdown-it[markdown-it]

  Custom editor and highlight via https://github.com/highlightjs/highlight.js/[highlight.js].

  * markup implementation: custom
  * website: https://markdown-it.github.io
  * source: https://github.com/markdown-it/markdown-it
  * WYSIWYG: no
  * preview scroll sync: yes
  * editor hangs on large input: yes
* Quill.md
  * website: https://quilljs.com
  * source: https://github.com/quilljs/quill/
  * demo: https://pandao.github.io/editor.md
  * WYSIWYG: yes
  * markdown output: no https://github.com/quilljs/quill/issues/74
* https://ui.toast.com/tui-editor/
* https://www.froala.com/wysiwyg-editor

= Error reporting
{parent=tooling}

A lot of effort has been put into making error reporting as good as possible in Cirodown, to allow authors to quickly find what is wrong with their source code.

Error reporting is for example tested with `assert_error` tests in \a[test.js].

Please report any error reporting bug you find, as it will be seriously tracked under the: https://github.com/cirosantilli/cirodown/issues?q=label%3Aerror-reporting+[`error-reporting` label].

Notably, Cirodown should never throw an exception due to a syntax error, as that prevents error messages from being output at all.

= Order of reported errors
{parent=error-reporting}

One important philosophy of the error reporting is that the very first message should be the root cause of the problem whenever possible: users should not be forced to search a hundred messages to find the root cause. In this way, the procedure:
* solve the first error
* reconvert
* solving the new first error
* reconvert
* etc.
should always deterministically lead to a resolution of all problems.

Error messages are normally sorted by file, line and column, regardless of which conversion stage they happened (e.g. a tokeniser error first gets reported before a parser error).

There is however one important exception to that: broken internal cross references are always reported last.

For example, consider the following syntactically wrong document:
```
= a

\x[b]

``
== b
```
Here we have an unterminated code block at line 5.

However, this unterminated code block leads the header `b` not to be seen, and therefore the reference `\x[b]` on line 3 to fail.

Therefore, if we sorted naively by line, the broken reference would shoe up first:
``
error: tmp.ciro:3:3: cross reference to unknown id: "b"
error: tmp.ciro:5:1: unterminated literal argument
``

But in a big document, this case could lead to hundreds of undefined references to show up before the actual root unterminated literal problem.:
``
error: tmp.ciro:3:3: cross reference to unknown id: "b"
error: tmp.ciro:4:3: cross reference to unknown id: "b"
error: tmp.ciro:5:3: cross reference to unknown id: "b"
...
error: tmp.ciro:1000:1: unterminated literal argument
``

Therefore, we force undefined references to show up last to prevent this common problem:
``
error: tmp.ciro:1000:1: unterminated literal argument
error: tmp.ciro:3:3: cross reference to unknown id: "b"
error: tmp.ciro:4:3: cross reference to unknown id: "b"
error: tmp.ciro:5:3: cross reference to unknown id: "b"
...
``

= Developing Cirodown
{parent=cirodown}

= Run Cirodown master
{parent=developing-cirodown}

Install master globally on your machine:
``
git clone https://github.com/cirosantilli/cirodown
cd cirodown
npm link
npm link cirodown
npm run build-assets
``
so you can now run the `cirodown` command from any directory in your computer, for example to convert the cirodown documentation itself:
``
cirodown .
``
We also have a shortcut for `npm link` and `npm link cirodown`:
``
npm run link
``

`npm link link` produces symlinks so that any changes made to the Git source tree will automatically be visible globally, see also: https://stackoverflow.com/questions/28440893/install-a-locally-developed-npm-package-globally The symlink structure looks like:
``
/home/ciro/cirodown/node_modules/cirodown -> /home/ciro/.nvm/versions/node/v14.17.0/lib/node_modules/cirodown -> /home/ciro/cirodown
``

As mentioned at \x[useless-knowledge], most users don't want global installations of Cirodown. But this can be handy during development, as you can immediately see how your changes to Cirodown source code affect your complex example of interest. For example, Ciro developed a lot of Cirodown by hacking https://github.com/cirosantilli/cirosantilli.github.io directly with Cirodown `master`.

Just remember that if you add a new dependency, you must redo the symlinking business:
``
npm install <dependency>
npm run link
``
Asked if there is a better way at: https://stackoverflow.com/questions/59389027/how-to-interactively-test-the-executable-of-an-npm-node-js-package-during-develo[]. The symlink business can be undone with:
``
npm unlink
rm node_modules/cirodown
``

= Test system
{parent=developing-cirodown}

Run all tests:
``
npm test
``

List all tests:
``
node node_modules/mocha-list-tests/mocha-list-tests.js main.js
``
as per: https://stackoverflow.com/questions/41380137/list-all-mocha-tests-without-executing-them/58573986#58573986[].

Run just one test by name:
``
npm test -- -g 'one paragraph'
``
as per: https://stackoverflow.com/questions/10832031/how-to-run-a-single-test-with-mocha TODO: what if the test name is a substring?

Step debug during a test run. Add the statement:
``
debugger;
``
to where you want to break in the code, and then:
``
node inspect ./node_modules/.bin/mocha test --ignore-leaks -g 'p with id before'
``
Note however that this does not work for tests that run the `cirodown` executable itself, since those spawn a separate process. TODO how to do it? Tried along:
``
    const out = child_process.spawnSync('node', ['inspect', 'cirodown'].concat(options.args), {
      cwd: tmpdir,
      input: options.stdin,
      stdio: 'inherit',
    });
``
but not working, related: https://stackoverflow.com/questions/23612087/gulp-target-to-debug-mocha-tests So for now, we are just printing the command being run as in:
``
cmd: cd /tmp/cirodowniyLn7v && cirodown --split-headers .
``
so you can just re-run it manually with `node inspect` as in:
``
cd /tmp/cirodowniyLn7v && node inspect "$(which cirodown)" --split-headers .
``
This works since the `tmp` directory is not deleted in case of failure.

= Overview of files in this repository
{parent=developing-cirodown}

Source files:
* \a[index.js]: main code. Must be able to run in the browser, so no Node.js specifics. Exposes the central `convert` function. You should normally use the packaged `dist/cirodown.js` when using cirodown as an external dependency.
* \a[cirodown]: CLI executable. Is basically just a CLI interface frontend to `convert`
* \a[test.js]: contains all the Mocha tests, see also: \x[test-system]
* \a[README.md]: minimal Markdown README until GitHub / NPM support Cirodown :-)
* \a[cirodown_runtime.js]: JavaScript functionality to be included in the final documents to enable interactive document features such as the \x[table-of-contents]. You should use the packaged `dist/cirodown_runtime.js` instead of this file directly however.
* \a[main.scss] this file simply contains the customized CSS for https://cirosantilli.com/cirodown/[] and does not get otherwise distributed with Cirodown, see: \x[css]

Generated files:
* `dist/` contains fully embedded packaged versions that work on browsers as per common JavaScript package naming convention:
  * `dist/cirodown.js`: Webpack output JavaScript of the converter for browser usage. Generated with `npm run webpack`. The source entrypoint for it is located at \a[index.js]. Contains the code of every single dependency used from `node_modules`. This is notably used for the live-preview of a \x[browser-editor-with-preview].
  * `dist/cirodown_runtime.js`: similar `dist/cirodown.js`, but contains the converted output of \a[cirodown_runtime.js]. You should include this in every Cirodown HTML output.
  * `dist/cirodown.css`: minimized CSS needed to view Cirodown output as intended. Embeds all Cirodown CSS dependencies, notably the KaTeX CSS without which \x[mathematics] displays as garbage. This file is built with \a[build-sass], and the Sass entry point is \a[cirodown.scss]. Ideally, we would also use Webpack for this file, but we weren't able to get it working yet due to KaTeX font issues: https://github.com/cirosantilli/cirodown/issues/157 | https://github.com/KaTeX/KaTeX/discussions/3115

= The `out` directory
{parent=overview-of-files-in-this-repository}

Cirodown stores some metadata and outputs it generates/needs inside the `./out/` directory that it creates inside the \x[outdir].

Overview of files it contains:
* `db.sqlite3`: \x[internal-cross-file-reference-internals]
* `publish`: a git clone of the source of the main repository to ensure that untracked files won't accidentally go into the output
  * `publish/out/db.sqlite3`: like `out/db.sqlite3` but from the clean clone of `out/publish`
  * `publish/out/publish`: the final generated output directory that gets published, e.g. as in \x[publish-to-github-pages]

= Conversion process overview
{parent=developing-cirodown}

Conversion follows the following steps:
* tokenizer
* parser
* post processing: takes parser output, and modifies the parse tree to achieve several functionalities
* render (AKA conversion). Currently has to be done multiple times to support tags via \x[x-child-argument] which only gets indexed at render time

= Autogenerated tests
{parent=conversion-process-overview}

The following scripts generate parametrized Cirodown examples that can be used for performance or other types of interactive testing:
* \a[generate-deep-tree]:

  ``
  ./generate-deep-tree 2 5 > deep_tree.tmp.ciro
  ./cirodown deep_tree.tmp.ciro
  ``

  Originally designed to be able to interactively play with a huge \x[table-of-contents] to streamline JavaScript open close interaction.

= generate-paragraphs
{parent=autogenerated-tests}

``
./generate-paragraphs 10 > main.ciro
``

Output:
``
0

1

2

3

4

5

6

7

8

9
``

= Performance
{parent=developing-cirodown}

= `--debug-perf`
{parent=performance}

print performance statistics to stderr, for example
``
./cirodown --debug-perf README.ciro
``
could output:
``
perf start: 181.33060800284147
perf tokenize_pre: 181.4424349963665
perf tokenize_post: 318.333980999887
perf parse_start: 319.1866770014167
perf post_process_start: 353.5477180033922
perf post_process_end: 514.1527540013194
perf render_pre: 514.1708239987493
perf render_post: 562.834307000041
perf end: 564.0349840000272
perf convert_input_end 566.1234430000186
perf convert_path_pre_sqlite 566.1564619988203
perf convert_path_pre_sqlite_transaction 566.2528780028224
perf convert_path_post_sqlite_transaction 582.256645001471
perf convert_path_end 582.3469280004501
``

= Speed comparison to other markup language implementations
{parent=performance}

One quick and dirty option is to use `generate-paragraphs` which generates output compatible for most markup languages:
``
./generate-paragraphs 100000 > tmp.ciro
``

On Ubuntu 20.04 \a[https://cirosantilli.com/linux-kernel-module-cheat/#p51][Lenovo ThinkPad P51] for example:
* Cirodown 54ba49736323264a5c66aa5d419f8232b4ecf8d0 + 1, Node.js v12.18.1
  ``
  time ./cirodown tmp.ciro
  ``
  outputs:
  ``
  real    0m5.104s
  user    0m6.323s
  sys     0m0.674s
  ``
* Asciidoctor 2.0.10, Ruby 2.6.0p0:
  ``
  cp tmp.ciro tmp.adoc
  time asciidoctor tmp.adoc
  ``
  outputs:
  ``
  real    0m1.911s
  user    0m1.850s
  sys     0m0.060s
  ``
* https://github.com/commonmark/cmark[cmark] 0.29.0:
  ``
  cp tmp.ciro tmp.md
  time cmark tmp.md > tmp.md.html
  ``
  outputs:
  ``
  real    0m0.091s
  user    0m0.070s
  sys     0m0.021s
  ``
  Holy cow, it is 200x faster than Asciidoctor!
* https://github.com/markdown-it/markdown-it[markdown-it] at 5789a3fe9693aa3ef6aa882b0f57e0ea61efafc0 to get an idea of a JavaScript markdown implementation:
  ``
  time markdown-it tmp.md > tmp.md.html
  ``
  outputs:
  ``
  real    0m0.361s
  user    0m0.590s
  sys     0m0.060s
  ``
* `cat` just to find the absolute floor:
  ``
  time cat tmp.ciro > tmp.tmp
  ``
  outputs:
  ``
  real    0m0.006s
  user    0m0.006s
  sys     0m0.000s
  ``

= Internals API
{parent=developing-cirodown}

Tokenized token stream and AST can be obtained as JSON from the API.

Errors can be obtained as JSON from the API.

Everything that you need to write Cirodown tooling, is present in the main API.

All tooling will be merged into one single repo.

= The `\Toplevel` implicit macro
{id=toplevel}
{parent=internals-api}

Every Cirodown document is implicitly put inside a `\Toplevel` document and:
* any optionally given arguments at the very beginning of the document will be treated as arguments of the `\Toplevel` macro
* anything else will be put inside the `content` argument of the `\Toplevel` macro

E.g., a Cirodown document that contains:
``
{title=My favorite title.}

And now, some content!
``

is morally equivalent to:
``
\Toplevel{title=My favorite title.}
[
And now, some content!
]
``
In terms of HTML, the `\Toplevel` element corresponds to the `<html>`, `<head>`, `<header>` and `<footer>` elements of a document.

Trying to use the `\Toplevel` macro explicitly in a document leads to an error.

= HTML document title
{c}
{parent=internals-api}

* if the `title` argument of `toplevel` is given, use that
* otherwise, if the document has a `\H[1]`, use the title of the first such header
* otherwise use a dummy value

= CSS
{c}
{parent=developing-cirodown}

Our CSS is located at \a[main.scss] and gets processed through https://sass-lang.com[Sass].

To generate the CSS during development after any changes to that file, you must run:
``
npm run sass
``
which generates the final CSS file:
``
main.css
``

You then need to explicitly include that `main.css` file in your \x[template]. For example, our \a[main.liquid.html] contains a line:
``
<link rel="stylesheet" type="text/css" href="{{ root_relpath }}main.css">
``
where `root_relpath` is explained under \x[template]{full}.

= Formal grammar
{parent=developing-cirodown}

TODO. Describe Cirodown's formal grammar, and classify it in the grammar hierarchy and parsing complexity.

= Release procedure
{parent=developing-cirodown}

= Do the release
{parent=release-procedure}

Before the first time you release, you need to login to NPM with:
``
npm login
``

Then, every new release can be done automatically with the \a[release] script, e.g. to release a version 0.7.2:
``
./release 0.7.2
``
That script does the following actions, aborting immediately if any of them fails:
* runs \x[test-system][the tests]
* publishes this documentation
* updates `version` in `package.json`
* creates a release commit and a git tag for it
* pushes the source code
* publishes the NPM package

= Out-of-box testing
{parent=release-procedure}

After publishing, a good minimal sanity check is to ensure that you can render the template as mentioned in \x[play-with-the-template]:
``
cd ~
# Get rid of the global npm link development version just to make sure it is not being used.
npm uninstall cirodown
git clone https://github.com/cirosantilli/cirodown-template
cd cirodown-template
npm install
npx cirodown .
firefox index.html
``
